Chrome 扩展 消息传递Message

content_scriptsbackground 传递

content_scripts.js

   var msg = {
            type: "PD-article-information",
            title : wuliuInfo,
            postDate : PD(".order-row").text(),
            url: document.URL
        };
        
  chrome.runtime.sendMessage(msg);      
        

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendRequest){
    if(request.type!=="PD-article-information")
        return;
    articleData = request;
    alert(articleData.title);
});

走了一下 可以走通;

到反过来传递消息 就 错误不知道在哪了

backgroundcontent_script 发送事件消息

content_scripts.js

chrome.runtime.onMessage.addListener(
           function(request, sender, sendResponse) {
             console.log(sender.tab ?
                         "from a content script:" + sender.tab.url :
                         "from the extension");
             if (request.greeting == "hello")//判断是否为要处理的消息
               sendResponse({farewell: "goodbye"});
         });

background.js

 chrome.tabs.query(
      {active: true, currentWindow: true}, 
      function(tabs) {
            chrome.tabs.sendMessage(
              tabs[0].id, 
             {greeting: "hello"}, 
             function(response) {
                     console.log(response.farewell);
         });
    });
阅读 5.5k
1 个回答

你第三段代码贴错了还是写错了?不是应该是注册一个事件监听器吗,怎么是发送消息的代码?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题