0

I'm new to this and was looking online for something that helped and could not reach a good response :( I'm trying to get a specific request url form a website and store it in a variable in my contentScript file.

To clarify, I don't have a specific error message, I simple can't find a way to communicate the webResponse from background.js with the contentScript.js

my code is as follows:

backgorund.js

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
    switch (request.message) {
      case 'GET_REQUEST_URL':
        //Catch request URL
        let requestUrl = '';
        chrome.webRequest.onCompleted.addListener(
          (response) => { sendResponse(response.url); },
          {
            urls: [
              'https://example1*',
              'https://example2*',
              'https://example3*'
            ]
          }
        );
        break;
    }
  }
);

contentScript.js

let requestUrl = '';
chrome.runtime.sendMessage(
  { message: "GET_REQUEST_URL" },
  response => { requestUrl = response; }
);

If I run the chrome.webRequest.onCompleted outside the switch case I get the url needed (see code below), I just can't pass it to contentScript :(

let requestUrl = '';
chrome.webRequest.onCompleted.addListener(
  (response) => { requestUrl = response.url; },
  {
    urls: [
      'https://example1*',
      'https://example2*',
      'https://example3*'
    ]
  }
);

Thank you for the help!

UPDATE WORKING CODE:

backgorund.js

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
    switch (request.message) {
      case 'GET_REQUEST_URL':
        //Catch request URL
        let requestUrl = '';
        chrome.webRequest.onCompleted.addListener(
          (response) => { sendResponse(response.url); },
          {
            urls: [
              'https://example1*',
              'https://example2*',
              'https://example3*'
            ]
          }
        );
        return true;
    }
  }
);

contentScript.js

let requestUrl = '';
chrome.runtime.sendMessage(
  {
    message: "GET_REQUEST_URL",
    callback: response => { response }
 },
  response => { requestUrl = response; }
);
Marta
  • 1
  • 2
  • 1) Replace `break` with `return true` , 2) In the content script use `response` *inside* the callback because it's asynchronous. – wOxxOm Jan 04 '23 at 11:49

0 Answers0