Question

Is it possible to transfer an object between background and content script within a browser extension?

I want my background script to handle my in-browser storage. My content script should trace user interactions and store them. Therefore I planed to use a singleton pattern to get an instance if my "abstract" storage engine from the background script to avoid syncing problems if an user records interactions and manages his data via the browser extensions' UI at the same time.

My first try looks like this:

background script

var StorageEngine, _StorageEngine;

StorageEngine = (function() {
  var _instance;
  function StorageEngine() {}
  _instance = null;
  StorageEngine.getInstance = function() {
    return _instance != null ? _instance : _instance = new _StorageEngine;
  };
  return StorageEngine;
})();

_StorageEngine = (function() {
  function _StorageEngine() {}
  _StorageEngine.prototype.sayMyName = function(message) {
    return 'hello ' + message;
  };
  return _StorageEngine;
})();

content script

(function() {
  kango.invokeAsync('StorageEngine.getInstance', function(val) {
    var asd;
    if (val) {
      debugger;
    }
    asd = val.sayMyName('Alice');
    return kango.console.log(asd);
  });
}).call(this);

val isn't undefined it's an object if googles debugger is trustworthy but the function sayMyName is undefined.

Was it helpful?

Solution

You can't pass functions from background to content script because of browsers limitations, you can pass only JSON serializable data.

Try to use storage in this way:

// background script
var storage = StorageEngine.getInstance();

// content script
kango.invokeAsync('storage.sayMyName', 'Alice', function(val) {
    kango.console.log(val);
});

OTHER TIPS

Chrome extensions content scripts live in isolated worlds, meaning they share DOM, but have separate JavaScript sandboxes.

So your kango.invokeAsync function and all variables are not reachable to content script. If you want to make use of page JS Variables and functions define Content scripts as here.

var script = document.createElement('script'); // Create a Script Tag
script.src = chrome.extension.getURL("yourscript.js"); //Fetch the content script
script.onload = function () {
    this.parentNode.removeChild(this); //Remove script after script executed
};
(document.head || document.documentElement).appendChild(script); //ADD script tag 
                                                       //to head or Html element

Your code doesnot has any communication mechanism between content scripts and background page. Add a message communication system for all your functional requirements.

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top