0

I am trying to send a variable from a file called popup.js to another called content.js.

I've tried using localStorage, but the content.js file receives it as null (I am certain that the popup.js file declares it as string because I output its type from the popup to the console). Now, I am using chrome.runtime to send the variable to the content.js, but what I'm trying now is not giving me anything, not even any errors.

This is my popup.js:

$(function(){
  $('#submit').click(function(){
  var amount = $('#repitions').val();
    if (amount){
      var x = JSON.stringify(amount);
      chrome.runtime.sendMessage({y: x});
    }
  });
});

And this is the section of the content.js file that receives the message:

chrome.runtime.onMessage.addListener(function(request){
    z = request;
    alert(z); 
});

There is something I'm doing wrong?. Thank you for reading my question.

robe007
  • 3,523
  • 4
  • 33
  • 59
Cracka
  • 11
  • 2

1 Answers1

0

In terms of scope, there is no concept of "files" in JavaScript. The whole javascript code, whether is implemented in one file or 200 files runs in the same environment. There are ways to simulate namespaces or similar conepts but I don't think that's your case.

I think you can simply implement a method in the content script file and call it from your popup.js code, passing your variable.

Example:

  • popup.js
...
$(function(){
  $('#submit').click(function(){
  var amount = $('#repitions').val();
    if (amount){
      Content.processAmount(amount);
    }
  });
});
...
  • content.js
var Content = {
    processAmount: function(amount){
        //do something here
        console.log(amount);
    }
    ...
}
robe007
  • 3,523
  • 4
  • 33
  • 59
ilrenzo
  • 31
  • 1
  • 7
  • It says that Content (in the popup) is not defined – Cracka Apr 01 '21 at 01:46
  • This answer is completely wrong because extensions are different: these files run in completely different processes. The content script runs in the web page whereas the popup is a separate page with a chrome-extension:// URL. See the linked duplicate topic for the correct solution. – wOxxOm Apr 01 '21 at 02:44
  • Yes @wOxxOm you're right. I've completely missed that she/he was talking about a chrome extension. My fault. – ilrenzo May 05 '21 at 20:53