InfinityCounter
InfinityCounter

Reputation: 384

Chrome Extension Can't call any methods in background page

I have been trying for a while but I'm unable to call any methods on my background page js file.

My manifest looks like this:

{
  "name" : "First chrome extension",
  "version" : "0.0.1",
  "manifest_version" : 2,
  "browser_action" : {
    "default_title" : "Practice",
    "default_icon" : {
      "16" : "assets/images/icon16.png",
      "24" : "assets/images/icon24.png",
      "32" : "assets/images/icon32.png"
    },
   "default_popup" : "popup.html"
  },
  "background" : {
    "scripts" : ["background.js"]
  },
  "content_scripts" : [{
    "matches" : ["*://*/*"], 
    "js" : [
      "assets/js/jquery-3.2.1.slim.min.js",
      "assets/js/content.js"
     ]
  }],
  "permissions" : [
    "activeTab",
    "storage"
  ]
}

background.js:

function test()
{
  return 'called';
}

assets/js/popup.js:

console.log(chrome.extension.getBackgroundPage().test());

Most of the examples I saw used the chrome.extension.getBackgroundPage method to retrieve the background but whenever I try this method it tells me the method or any other variable I set in background.js is undefined and they're not present on the returned window object.

I also tried using the messaging API like so: background.js

"use strict";

const test = function() {
    console.log(1);
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse){
    console.log(request);  
    if(request.msg.toLowerCase()  === "bg-test") test();
  }
);

assets/js/popup.js:

$(function() {
  const btn = '#en-dis-btn';
  $(btn).click(function(e){
    e.preventDefault();
    chrome.runtime.sendMessage({'msg' : 'bg-test'}, function(response) {
       console.log(response);
    });
  });
});

but the listener in background.js is never called. What could I be doing wrong? The background page is not null so it is loading something.

Upvotes: 0

Views: 851

Answers (1)

woxxom
woxxom

Reputation: 73846

According to the ECMA specification:

let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment.

When you declare a let/const variable globally in one page (the background page), the variable's LexicalEnvironment is scoped that page's global this (which equals the page's window) and another page (the popup) is clearly outside of that scope.

Use var foo = bar or function foo() {} declaration, which exposes it as a property of the window object so it's visible in another same-origin chrome-extension://*extensionID* page such as the popup page.

Upvotes: 1

Related Questions