Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions web/src/components/search-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,29 @@ import type { SearchEngine } from "@/lib/types";
* 顶部多引擎搜索框:引擎切换(下拉)、`/` 键全局聚焦、Enter 按 {q} 模板跳转。
*
* `openInNewTab`(站点设置 `searchNewTab`,默认开):开时结果在新标签页打开,
* 起始页与会话保留;关时沿用当前页跳转。两种方式对所有引擎(含自定义)一致生效。
* 起始页与会话保留;关时在当前页跳转。两种方式对所有引擎(含自定义)一致生效。
* 两条路径都不向搜索站发送 Referer(见 `navigateSameTabWithoutReferrer`)。
*/

/**
* 当前页跳转且不带 Referer:用临时锚点(`rel="noreferrer"`)点击完成导航。
*
* `window.location.href` 无法抑制来源,跨站跳转时浏览器按默认策略(
* strict-origin-when-cross-origin)会把本页 origin 作为 Referer 一起发出去。
* 锚点的 `rel="noreferrer"` 只作用于这一次导航(强制 no-referrer),因此不动
* 页面级 `<meta name="referrer">`,其它外跳与资源加载的 Referer 行为一律不变。
*/
export function navigateSameTabWithoutReferrer(url: string) {
const anchor = document.createElement("a");
anchor.href = url;
anchor.rel = "noreferrer";
anchor.target = "_self";
document.body.append(anchor);
anchor.click();
// 锚点是临时的:点击已触发导航,随即从 DOM 撤掉(不留空节点、不改布局)
anchor.remove();
}

export function SearchBar({
engines,
openInNewTab = true,
Expand Down Expand Up @@ -61,7 +82,7 @@ export function SearchBar({
window.open(url, "_blank", "noopener,noreferrer");
return;
}
window.location.href = url;
navigateSameTabWithoutReferrer(url);
};

return (
Expand Down
18 changes: 16 additions & 2 deletions web/test/public-page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ describe("PublicPage:搜索跳转方式跟随站点设置 searchNewTab", () =>
await user.type(screen.getByLabelText("搜索关键词"), "nav{enter}");
}

it("searchNewTab=false:搜索在当前页跳转(不新开标签)", async () => {
it("searchNewTab=false:搜索在当前页跳转,且不带 Referer(rel=noreferrer 锚点)", async () => {
seedWithEngines({ ...baseSettings, searchNewTab: false });
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
const location = { href: "http://localhost/start" };
Expand All @@ -172,12 +172,26 @@ describe("PublicPage:搜索跳转方式跟随站点设置 searchNewTab", () =>
writable: true,
value: location as unknown as Location,
});
// jsdom 里点锚点会触发未实现的导航:拦在 prototype 上,只记下被点的锚点
const clicked: HTMLAnchorElement[] = [];
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (
this: HTMLAnchorElement,
) {
clicked.push(this);
});

render(<PublicPage onOpenAdmin={vi.fn()} />);
await submitSearch();

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe("https://www.google.com/search?q=nav");
// 跳转交给挂了 rel=noreferrer 的临时锚点:这次导航不向搜索站发 Referer
expect(clicked).toHaveLength(1);
expect(clicked[0].rel).toBe("noreferrer");
expect(clicked[0].getAttribute("href")).toBe(
"https://www.google.com/search?q=nav",
);
expect(clicked[0].isConnected).toBe(false);
expect(location.href).toBe("http://localhost/start");
});

it("设置缺该字段(存量库)时按默认开:新标签打开", async () => {
Expand Down
96 changes: 80 additions & 16 deletions web/test/search-bar.test.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { SearchBar } from "@/components/search-bar";
import {
navigateSameTabWithoutReferrer,
SearchBar,
} from "@/components/search-bar";
import type { SearchEngine } from "@/lib/types";

/**
* 搜索跳转方式(站点设置 `searchNewTab`,默认开):
* - 开:`window.open(url, "_blank", "noopener,noreferrer")`,起始页与会话保留;
* - 关:沿用 `window.location.href` 当前页跳转。
* - 关:临时锚点(`rel="noreferrer"`)在当前页跳转,不带 Referer。
* 两种方式都在 submit 的公共分支里,切换引擎(含自定义引擎)后行为一致。
*/

Expand All @@ -31,22 +34,50 @@ const custom: SearchEngine = {

const engines = [google, custom];

/** jsdom 不实现真实导航:把 location 换成可读 href 的桩,断言跳转目标。 */
/**
* jsdom 不实现真实导航:把 location 换成桩。带写入计数——同页跳转若退回
* `window.location.href`,计数就会 > 0(那条路径压不住 Referer)。
*/
function stubLocation() {
const location = { href: "http://localhost/start" };
const state = { value: "http://localhost/start", writes: 0 };
const location = {
get href() {
return state.value;
},
set href(next: string) {
state.writes += 1;
state.value = next;
},
};
Object.defineProperty(window, "location", {
configurable: true,
writable: true,
value: location as unknown as Location,
});
return location;
return state;
}

/**
* jsdom 里点锚点会触发未实现的导航:拦在 prototype 上,只记下「点的是哪个锚点」,
* 用来断言同页跳转真的走的是带 rel="noreferrer" 的锚点。
*/
function stubAnchorClick() {
const clicked: HTMLAnchorElement[] = [];
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (
this: HTMLAnchorElement,
) {
clicked.push(this);
});
return clicked;
}

let openSpy: ReturnType<typeof vi.spyOn>;
let location: { href: string };
let location: { value: string; writes: number };
let clickedAnchors: HTMLAnchorElement[];

beforeEach(() => {
location = stubLocation();
clickedAnchors = stubAnchorClick();
openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
});

Expand Down Expand Up @@ -86,7 +117,9 @@ describe("SearchBar 跳转方式:默认新标签打开", () => {
"_blank",
"noopener,noreferrer",
);
expect(location.href).toBe("http://localhost/start");
expect(location.writes).toBe(0);
// 新标签路径不借道同页锚点
expect(clickedAnchors).toHaveLength(0);
});

it("显式 openInNewTab={true} 同为新标签打开", async () => {
Expand All @@ -99,7 +132,8 @@ describe("SearchBar 跳转方式:默认新标签打开", () => {
"_blank",
"noopener,noreferrer",
);
expect(location.href).toBe("http://localhost/start");
expect(location.writes).toBe(0);
expect(clickedAnchors).toHaveLength(0);
});

it("切换引擎后仍是新标签打开,且用该引擎的模板", async () => {
Expand All @@ -113,40 +147,70 @@ describe("SearchBar 跳转方式:默认新标签打开", () => {
"_blank",
"noopener,noreferrer",
);
expect(location.href).toBe("http://localhost/start");
expect(location.writes).toBe(0);
expect(clickedAnchors).toHaveLength(0);
});
});

describe("SearchBar 跳转方式:关闭开关后当前页跳转", () => {
it("回车在当前页跳转,不新开标签", async () => {
describe("SearchBar 跳转方式:关闭开关后当前页跳转(且不带 Referer)", () => {
it("回车在当前页跳转:走 rel=noreferrer 的临时锚点,不新开标签、不写 location", async () => {
render(<SearchBar engines={engines} openInNewTab={false} />);

await search("react hooks");

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe("https://www.google.com/search?q=react%20hooks");
expect(clickedAnchors).toHaveLength(1);
const [anchor] = clickedAnchors;
// rel=noreferrer 是「这次导航不发 Referer」的唯一依据;location.href 压不住来源
expect(anchor.rel).toBe("noreferrer");
expect(anchor.target).toBe("_self");
expect(anchor.getAttribute("href")).toBe(
"https://www.google.com/search?q=react%20hooks",
);
// 临时锚点用完即撤;当前页本身不动(导航由锚点接管)
expect(anchor.isConnected).toBe(false);
expect(location.value).toBe("http://localhost/start");
expect(location.writes).toBe(0);
});

it("切换引擎后仍是当前页跳转,且用该引擎的模板", async () => {
it("切换引擎后仍是当前页跳转,且用该引擎的模板(同样 rel=noreferrer)", async () => {
render(<SearchBar engines={engines} openInNewTab={false} />);

await switchEngine("自建搜索");
await search("nav 导航");

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe(
expect(clickedAnchors).toHaveLength(1);
const [anchor] = clickedAnchors;
expect(anchor.rel).toBe("noreferrer");
expect(anchor.getAttribute("href")).toBe(
"https://search.example.com/?wd=nav%20%E5%AF%BC%E8%88%AA&lang=zh",
);
expect(location.writes).toBe(0);
});
});

describe("navigateSameTabWithoutReferrer", () => {
it("点一个挂了 rel=noreferrer 的锚点,点完从 DOM 撤掉、不留痕迹", () => {
navigateSameTabWithoutReferrer("https://example.com/?q=1");

expect(clickedAnchors).toHaveLength(1);
const [anchor] = clickedAnchors;
expect(anchor.rel).toBe("noreferrer");
expect(anchor.getAttribute("href")).toBe("https://example.com/?q=1");
expect(anchor.isConnected).toBe(false);
expect(location.writes).toBe(0);
});
});

describe("SearchBar 边界:空查询", () => {
it("空查询 / 纯空格不跳转、不新开标签", async () => {
it("空查询 / 纯空格不跳转、不新开标签、不点锚点", async () => {
render(<SearchBar engines={engines} />);

await search(" ");

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe("http://localhost/start");
expect(clickedAnchors).toHaveLength(0);
expect(location.value).toBe("http://localhost/start");
});
});
Loading