javascript - 如何将 chrome 扩展背景数据转为 javascript 函数

标签 javascript google-chrome google-chrome-extension background send

我正在开发 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/

相关文章:

javascript - 检测用户何时滚动到看到页脚之前的像素

html - 如何在右对齐的表格行中忽略 Google Chrome 中的额外空白?

javascript - 发出多个异步获取请求并找出哪个请求包含字符串匹配

javascript - Chrome 扩展 JavaScript 错误

javascript - 如何将 websocket 推送定时器嵌入到网页中?

javascript - mustache 模板可以进行模板扩展吗?

javascript - 进程间的 NodeJs 共享对象

google-chrome - Chrome 未报告 CSP 违规行为

javascript - Chrome扩展开发: Call a method in popup from background_html

javascript - 检查选项卡是否存在并使其处于事件状态;否则创建它