我正在开发 chrome 扩展。我的项目有index.html、index.js 和background.js。
"content_scripts": [ {"js": [ "index.html" ], ],
"background": { "scripts":["background.js"], }
当index.js调用window.open(url)时,backgrund.js捕获新的url 像下面这样
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
alert(tab.url);
}});
所以我想将 tab.url 传递给 index.js 的函数(无论如何) 是否可以 ?我该如何调用它?
如果您知道操作方法或引用页面
请回答,祝你有美好的一天
最佳答案
要执行您想要的操作,您需要在扩展组件之间使用消息传递。
首先,您需要将 tabs
权限添加到 manifest.json
中。我还在你的 manifest.json
中发现了一些错误,检查一下,你想要的是这样的:
{
"manifest_version": 2,
"name": "Extension name",
"description": "Your description...",
"version": "1",
"permissions": [
"<all_urls>",
"tabs"
],
"background": { "scripts": ["background.js"] }
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content_script.js"]
}
]
}
然后,在 background.js
中,您将向 content_script.js
发送一条消息,如下所示:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.sendMessage(tabId, {message: "do something", url: tab.url});
}
});
在您的 content_script.js
中,您将收听该消息并采取相应的行为:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.message === "do something") {
alert('Got the url:', request.url); // here is the url you sent from background.js
// do what you want
}
});
<小时/>
这是documentation link欲了解更多信息。
关于javascript - 如何将 chrome 扩展背景数据转为 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26345111/