Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable from background to popup on Chrome extension

I want to make a simple extension, which is passing a variable from background to popup. The problem is, I get 'undefined' response.

Manifest:

{
  "name": "Get var",
  "description": "get var",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "browser_action": {
    "default_title": "Get that variable",
    "default_popup": "popup.html"
  },
  "manifest_version": 2
}

background.js

 var myURL = 'aaa';

popup.html

<!doctype html>
<html>
  <head>
    <script src="popup.js"></script>
  </head>
  <body>
  </body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function () {
   var bg = chrome.extension.getBackgroundPage();
    var myURL = bg.myURL;
  alert(myURL)

});
like image 551
Kuzgun Avatar asked Dec 13 '13 15:12

Kuzgun


1 Answers

Your code (exactly as you posted it in your question) is correct and should work fine. (In fact when I created a sample extension using the code you provided, it did work as expected.)
You either accidentaly changed something when copying-pasting the actual code or there is something else messing things up (something you left out of your post).


BTW, I would suggest looking into event-pages (i.e. non-persistent background-pages) which are more resource-friendly. Keep in mind, that moving to an event-page would require some changes in order for the code to work:

document.addEventListener('DOMContentLoaded', function () {
    chrome.runtime.getBackgroundPage(function (bg) {
        var myUrl = bg.myUrl;
        alert(myUrl);
    });
});

Note: I do not in any way imply that the reason you receive undefined is that you use a persistent background-page. The code you posted should work fine with a persistent background-page - it is just better practice to use an event page (whenever possible).

like image 158
gkalpak Avatar answered Nov 01 '22 03:11

gkalpak