您可以将该 iframe 嵌入到您打开的每个页面的 DOM 结构中。不幸的是,除了默认弹出窗口之外,Google 没有提供任何解决方案,该弹出窗口在第一次点击外部时会消失。另一方面,您需要每页运行一个内容脚本实例,这可能意味着将运行数百个(至少对我来说,因为我是一个强迫性的新标签打开者)。
这是其中一种方法,您可以如何处理。
第 1 步。 正如我已经说过的,点击图标的默认操作是打开一个弹出窗口。您可以通过在 manifest.json 中包含以下条目来禁用该行为:
"browser_action": {},
第 2 步。 接下来是创建在每个页面上运行的内容脚本。在您的清单中,它看起来像这样:
"content_scripts": [
{
"run_at": "document_end",
"matches": ["*://*/*"],
"js": ["path/to/your/content/script.js"]
}
],
第 3 步。
您的内容脚本应该将您提到的 iframe 嵌入到当前打开的页面中(当 DOM 完全加载时)。
window.addEventListener('load', function load(event) {
var iframe = document.createElement('iframe');
/* some settings, these are mine */
iframe.style.width = "250px";
iframe.style.background = "#eee";
iframe.style.height = "100%";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "1000000000000000";
iframe.frameBorder = "none";
/* end of settings */
iframe.src =
chrome.runtime.getURL("path/to/contents/of/your/iframe.html");
document.body.appendChild(iframe);
});
第 4 步。
您必须确保人们可以访问iframe.html。将此行添加到您的清单文件中:
"web_accessible_resources": ["path/to/contents/of/your/iframe.html"],
(或者如果该文件已经存在,则将该文件添加到列表中。
第 5 步。
在您的内容脚本中创建一个知道如何隐藏 iframe 的函数。类似的东西:
function toggle_iframe() {
if (iframe.style.width == "0px"){
iframe.style.width="250px";
} else {
iframe.style.width="0px";
}
}
现在,唯一剩下的就是知道何时调用它。
第 6 步。
不幸的是,后台脚本是唯一可以获取有关单击的扩展图标信息的地方。将此 sn-p 添加到您的后台脚本中:
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, { action: "must_toggle_iframe" });
})
});
当图标被点击时,它会发送一条消息。
第 7 步。
最后一部分是允许您的内容脚本接收该消息。您的内容脚本需要一个监听器。
chrome.runtime.onMessage.addListener(function(msg, sender) {
if (msg.action == "must_toggle_iframe"){
toggle_iframe();
}
}
当然,解决方案并不理想,但您可以改进它。例如,通过在chrome.storage.local/chrome.storage.sync 中记住 iframe 是否已隐藏。