0

Hi all, I have a content script that deals with webpages content. Then I have a background script that I use to fetch other pages of that domain. I'd like to perform some DOM analysis on otherpage's html without the need to visit it.

In content script I have:

var res="";
url='https://www.samedomain.com/otherpage.html';
var p = new Array(); p.push(url);
chrome.runtime.sendMessage(p, null,
    (response) => {
        // res contains otherpage's html I want
        // here it is correctly printed to console
        console.log(response.response);
        // dumb attempt to pass otherpage's html "outside"..
        res = response.response;
    }
);

// here "res" is empty...
console.log(res);

In service worker I have:

chrome.runtime.onMessage.addListener(
    function(arg, sender, sendresponse) {
        url = arg[0];
        fetch(url)
          .then(
            function(response) {
              if (response.status !== 200) {
                console.log('Response error: status Code is ' +
                  response.status);
                return;
              }
              return response.text()
            }
          ).then(function(text) {
            var p = {'response': text}; 
            sendresponse(p);
          })
          .catch(function(err) {
            console.log('Fetch Error: ', err);
          });
    }
    return true;
);

Googling around I understood that I have an async thing here, thus I can't use "res" outside as I planned; and so... is there any way to use response value outside (response) => { /* here */ } ?

Consider that I am a total newbie on this sort of things, please be kind. I searched a lot but I didn't find out what I have to do to freely use the service worker response data in my content script.

  • This is not specific to service workers or extensions. It's just a question of organizing asynchronous code i.e. you can put the outside code into a function and call it from the callback. – wOxxOm Dec 21 '21 at 16:19
  • Just to notify that the solution was just the one that @wOxxOm suggested: moving relevant stuff in a callback and call it from the async function with await. Doing this I also got rid of service worker code, fetching page directly in content script. – TheBlackbird Dec 22 '21 at 17:48

0 Answers0