如何将扩展背景的数据转换为javascript函数

时间:2014-10-13 16:58:21

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

我正在开发chrome扩展程序。我的项目有index.html,index.js和background.js。

  

“content_scripts”:[       {“js”:[“index.html”],    ],

     

“background”:{        “脚本”:[ “background.js”],    }

当index.js调用 window.open(url)时,backgrund.js会抓住新网址 如下所示

 chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {          
     if (changeInfo.status == 'complete') {
          alert(tab.url);
 }});

所以我想将tab.url传递给index.js的函数(无论如何) 可能吗 ?我怎么称呼它?

如果您知道操作方法或参考页

PLZ回答,祝你有愉快的一天

2 个答案:

答案 0 :(得分:3)

为了做你想做的事,我们需要在你的扩展组件之间使用消息传递。

首先,您需要向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以获取更多信息。

答案 1 :(得分:0)

您必须在内容脚本和后台脚本之间使用消息:

https://developer.chrome.com/extensions/messaging