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.
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);
});