从弹出窗口发送消息到内容脚本?

时间:2012-11-30 13:39:11

标签: javascript events google-chrome google-chrome-extension message

假设我想在google chrome扩展程序的弹出页面中点击按钮时运行内容脚本?

我尝试了以下内容:

//popup.js
document.addEventListener('DOMContentLoaded', function () {
  document.querySelector('button').addEventListener('click', clicked);
  main();
});

function clicked(){
    chrome.tabs.getCurrent(
        function(tab){
            console.log(tab);
            chrome.tabs.sendMessage(tab.id, "doSomething");     
        }
    ); 
}

在内容脚本中:

chrome.extension.onMessage.addListener(
    function(message, sender, sendResponse){
        console.log("hello world");
    }
);

问题是来自tab的回调中的chrome.tabs.getCurrent( )未定义。

2 个答案:

答案 0 :(得分:5)

您是否已为manifest.json中的选项卡授予权限,如此处所示。

 "permissions": [
    "tabs"
  ],

此外,以下代码返回的tab.id是弹出视图(不是内容脚本TAB.ID)

chrome.tabs.getCurrent(
        function(tab){
            console.log(tab);
            chrome.tabs.sendMessage(tab.id, "doSomething");     
        }
    ); 

如果您要向正在浏览的标签发送消息,请使用以下代码的tab.id,它会给出正确的结果

chrome.tabs.query({"status":"complete","windowId":chrome.windows.WINDOW_ID_CURRENT,"active":true}, function(tabs){
     console.log(JSON.stringify(tabs[0]));
     console.log(tabs[0].id); 
});

如果您需要更多信息,请告诉我

答案 1 :(得分:1)

@Sudarshan提供的答案是有效的,并且工作正常,但我刚刚找到了另一个问题的解决方案。我以为我把它放在这里:

function clicked() {
    chrome.tabs.executeScript(null,
      {code:"console.log('hello world');"});
}

它会注入并执行脚本。

相关问题