简体   繁体   中英

Can I send message from popup.js to content script without having a background script?

Up till now I am sending message from popup.js to background.js then to content.js in Chrome Extension. I am using background script as a intermediate.

I simply want to know if I can send message directly to content script without having a background script

Yes you can. The only difference between the popup and background pages is that the popup is only loaded while the popup is open. All the api's that you can use in the background page you can also use in the popup. So for example if you want to send a message to the content script in the current tab:

chrome.tabs.query({active:true,currentWindow:true},function(tabs){
  //tabs is an array even if there is only one result
  var message = "stuff goes here";
  chrome.tabs.sendMessage(tabs[0].id,message,function(response){
    //in case you want a response
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM