背景
我有一个带有浏览器操作的 Chrome 扩展程序,可以在新标签页中启动 index.html
。
我想更新扩展以在 popup 中打开 index.html
首先,然后包含一个按钮,用户可以单击该按钮以选择在新选项卡中打开应用。
我不希望此按钮在不是弹出窗口时显示(因为它没有意义),这意味着内容脚本需要知道它是否是弹出窗 Eloquent 能显示按钮。
问题
这是一个两部分的问题:
- Chrome 扩展程序弹出窗口如何知道它是一个弹出窗口?
- 如何在呈现弹出窗口之前将该信息传递给内容脚本?
我尝试过的
我尝试在 background.js
中使用 chrome.extension.getViews
来首先确定弹出窗口是否打开。然后,我向内容脚本发送一条消息,然后显示按钮。但是我还没有让它工作 - views
始终是一个空数组,并且内容脚本似乎从未收到过消息。
以下是我的 manifest.json
文件的相关部分:
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_icon": {
"19": "img/icon19.png",
"38": "img/icon38.png"
},
"default_title": "Super Simple Tasks",
"default_popup": "index.html"
}
这是我在我的 background.js
中尝试的:
// Get all popups
var views = chrome.extension.getViews({ type: "popup" });
// Send a message if there is a popup
if (views.length > 0){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "popup_open"}, function(response) {});
});
};
然后在我的内容脚本中,我监听消息,然后向正文添加一个类:
// Listen for the message
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action === 'popup_open') {
// My code here to show the button
}
});
最佳答案
在与 friend 交谈后,我发现了一个优雅的解决方案,它根本不涉及消息传递,甚至根本不涉及 background.js
脚本。
我可以在 manifest.json
中指定 ?popup=true
并在我的扩展的内容脚本中检查该参数。这是代码:
manifest.json
现在看起来像这样:
"browser_action": {
"default_icon": {
"19": "img/icon19.png",
"38": "img/icon38.png"
},
"default_title": "Super Simple Tasks",
"default_popup": "index.html?popup=true"
}
我的内容脚本中的以下代码(取自 this answer )检查 ?popup=true
。值得注意的是,此函数可以处理由 &
字符分割的多个 URL 参数。
function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
var isPopup;
isPopup = getUrlParameter('popup') === 'true';
最后,如果是弹窗的话,给body添加一个类:
$('body').toggleClass('popup', isPopup)
关于javascript - 如何确定 Chrome 扩展程序是否位于内容脚本的弹出窗口中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997428/