问题描述
当我单击content.js中的按钮时,我想打开扩展程序的选项页面。
我尝试了此操作,但没有打开options.html。
有人可以帮我吗? 预先感谢
manifest.json
"options_page": "options.html",
options.html
<p>hello world</p>
content.js
let btt = document.querySelector('.settings-icon-hk');
btt.addEventListener('click',function(){
window.open('../options.html')
})
解决方法
您不能直接从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") {
[...]
}
});
尽管如此,如果尝试使用options.html
打开 window.open('../options.html')
文件,浏览器将尝试在最可能不存在的服务器上打开该文件。您必须告诉浏览器打开扩展名的options.html
文件:
window.open(chrome.runtime.getURL('options.html'));
您必须告诉浏览器应该打开扩展名的option.html文件:
window.open(chrome.runtime.getURL('options.html'));
实际上,您不需要绕路而无需使用Chrome本身提供的功能:
chrome.runtime.openOptionsPage();
此功能的优点是可以识别open_in_tab
的“ manifest.json
”设置。
background.js:
chrome.runtime.onMessage.addListener((request) => {
if (request === "showOptions") {
chrome.runtime.openOptionsPage();
}
});
上找到此信息以及有关选项页面的更多信息。