【问题标题】:how to chrome extension background's data to javascript function如何将扩展背景的数据chrome扩展为javascript函数
【发布时间】:2014-12-08 07:41:14
【问题描述】:

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

“内容脚本”:[ {“js”:[“index.html”], ],

“背景”:{ “脚本”:[“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 的函数(无论如何) 可能吗 ?我怎么称呼它?

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

请回答,祝你有美好的一天

【问题讨论】:

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


    【解决方案1】:

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

    首先,您需要将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 了解更多信息。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-24
        • 2011-06-02
        • 2013-08-24
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        相关资源
        最近更新 更多