从弹出窗口发送消息到内容脚本? [英] Send message from popup to content script?

查看:138
本文介绍了从弹出窗口发送消息到内容脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试过以下操作:

  // 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(
函数(message,sender,sendResponse){
console.log(hello world);
}
);

问题是,在选项卡

解决方案

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

 权限:[

],

此外,以下代码返回的tab.id是弹出视图(NOT A CONTENT SCRIPT TAB.ID)

  chrome.tabs.getCurrent(
function标签){
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);
});

如果您需要更多信息,请通知我


Suppose I want to run a content script when I click a button in the popup page in a google chrome extension?

I have tried the following:

//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");     
        }
    ); 
}

And in the content script:

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

The problem is that the tab in the callback from chrome.tabs.getCurrent( ) is undefined.

解决方案

Have you given permissions for tabs in manifest.json as shown here.

 "permissions": [
    "tabs"
  ],

Moreover tab.id which the following code returns is of popup view (NOT A CONTENT SCRIPT TAB.ID)

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

If you want to send message to tab you are browsing use following code's tab.id, it gives correct results

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); 
});

Let me know if you need more information

这篇关于从弹出窗口发送消息到内容脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆