background发消息给content_scripts

//background.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
      {
          chrome.tabs.sendMessage(tabs[0].id,{from:'background发出的消息1',to:'content_scripts发出的消息2'}, function(response)
          {
              alert('收到content_scripts回复结果:'+response);
          });
      });

//content_scripts.js
chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        alert('我收到消息' +  request.from + request.to);
        sendResponse("content_scripts回复处理结果");
    }
);
background 访问 popup 如下(前提是 popup 已经打开)

var views = chrome.extension.getViews({ type: "popup" });
console.log("---views---", views);
if (views.length > 0) {
    console.log(views[0].location.href);
}

你可能感兴趣的:(chrome插件)