单击按钮CHROME EXTENSION时如何从内容脚本打开“选项”页面?

问题描述

当我单击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();
  }
});

您可以在https://developer.chrome.com/extensions/options

上找到此信息以及有关选项页面的更多信息。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...