0

I want to send a variable called "website_hostname" from the content-script to the background script. It contains the hostname of the current website you're on.

Content Script:

var website_hostname =  window.location.href;

//Code to send website_hostname 

Background Script:

// Get website_hostname 
fayzn
  • 1
  • There should be no need to send it because the background script can [read the URL directly](https://stackoverflow.com/questions/1979583/how-can-i-get-the-url-of-the-current-tab-from-a-google-chrome-extension). – wOxxOm Oct 11 '20 at 17:32

2 Answers2

1

I believe you can do that by using chrome onMessage.

in content,

    //content-script.js
    
     function notifyExtension() {
      chrome.runtime.sendMessage({"url": window.loaction.href});
    }
    //background.js
    chrome.runtime.onMessage.addListener(notify);

    function notify(message) {
         variable = message.url
      });
    }

I got this from https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage

0

Similar to what suggested to you in the previous answer But to do this it will be better use long lived connections port

Long-lived connections https://developer.chrome.com/extensions/messaging

var port = chrome.runtime.connect() Send a message to background page port.postMessage()

Listener

for response port.onMessage.addListener()
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
Ziv Adler
  • 169
  • 2
  • 11