简体   繁体   中英

Chrome extension function result from background.js to content script when ready

I am building a chrome extension to integrate 2 web applications to share data via REST API calls. The problem is one site (where I'm displaying the data) is on HTTPS and the other on HTTP so my content script will not execute AJAX GET requests from the HTTPS to the HTTP site. For a workaround I am using the background.js page to do all my calls to the HTTP site and then using chrome.storage I am passing information back to the content script with API results.

So far it's been working pretty good but now I'm at a point where I want to click a button I insert into HTTPS site, which calls background.js to fetch some data and when done, give it back to the content script. The problem is I don't know how to make the content script wait for the background.js call to be done before it tries to do its chrome.storage.sync.get call to get the data returned.

I keep thinking I need something like a callback function but I don't know how to wrap my head around those and I have no idea if that's what I even need. Any help would be appreciated!

To help anybody out there looking for the same thing I ended up using:

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

in content script:

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

more at https://developer.chrome.com/extensions/messaging

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