您无法直接从content.js 打开选项页面。您的浏览器将显示一条错误消息。相反,您需要向后台脚本发送消息并告诉它打开选项页面:
content.js:
let btt = document.querySelector(".settings-icon-hk");
btt.addEventListener("click", () => {
chrome.runtime.sendMessage("showOptions");
});
background.js:
chrome.runtime.onMessage.addListener((request) => {
if (request === "showOptions") {
[...]
}
});
尽管如此,如果您尝试使用 window.open('../options.html') 打开options.html 文件,浏览器将尝试打开服务器上很可能不存在该文件的文件。您必须告诉浏览器打开扩展名的options.html 文件:
window.open(chrome.runtime.getURL('options.html'));
你必须告诉浏览器它应该打开扩展的 option.html 文件:
window.open(chrome.runtime.getURL('options.html'));
其实你不需要走这条弯路,使用Chrome本身提供的功能:
chrome.runtime.openOptionsPage();
这个函数的优点是它可以识别manifest.json的“open_in_tab”设置。
background.js:
chrome.runtime.onMessage.addListener((request) => {
if (request === "showOptions") {
chrome.runtime.openOptionsPage();
}
});
您可以在 https://developer.chrome.com/extensions/options 找到有关此选项页面的更多信息