0

I'm using browserify to manage a Chrome extension, and while in general it appears to work well, there's a problem that comes with browserify embedding the library code in some wrappers. In particular, when accessing chrome.extensions.getBackgroundPage() from a Chrome extension plugin as described, e.g., here, not all (none?) of the background page's local variables can be accessed. This can be reproduced by anyone by wrapping background.js in

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
//[...]
},{}]},{},[1]);

as browserify does.

I'm not sure what kind of magic (if any) is behind chrome.extension.getBackgroundPage(), but maybe someone else has an idea.

Community
  • 1
  • 1
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • Please clarify whats the actual question and problem code. The one shown doesnt call get backgroundPage. Also the linked s.o. answer IS correct as it talks about a popup calling it. When it doenst work and requires messaging is when you try to use it from a content or injected script. – Zig Mandel Apr 29 '15 at 20:49
  • @ZigMandel Thanks for your comment. I tried to clarify the question to make it more easily reproducible for everyone. – Nico Schlömer Apr 29 '15 at 21:03
  • But from where is it calling getBackgroundPage from a popup js or a content or injected js? Must have that to answer – Zig Mandel Apr 29 '15 at 21:05
  • This is from the popup. – Nico Schlömer Apr 29 '15 at 21:24

2 Answers2

1

When you browserify a module (e.g., background.js), it gets wrapped in a function. Hence, all variables declared here in the style of

var iii = 123;

cannot be accessed from outside, and are in particular not exported to chrome.extensions.getBackgroundPage(). All variables that you would like to use elsewhere, must be declared global, e.g.,

global.iii = 123;
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
1

To add to Nico's answer, chrome.extensions.getBackgroundPage() always was something of a crude hack.

A better approach would be to decouple your popup and background code, and instead pass commands with Messaging and share data in chrome.storage.

Then this problem does not appear.

Xan
  • 74,770
  • 16
  • 179
  • 206