browser-extension-tools
v0.0.2
Published
Tools and utilities for developing browser extensions.
Downloads
3
Readme
Browser extension tools
Tools and utilities for developing browser extensions.
- Active tab management.
- Messaging between content-script and background scripts.
- RPC between content-script, background script and vice-versa.
Usage:
var MyExtension = require('browser-extension-tools');
// You define a content-script inline.
// This object will be serialized and sent to the
// browser tab. The activate and deactivate methods
// are called when your tab becomes active.
var MyContentScript = {
interval: null,
counter: 0,
async activate() {
// on activate you may register stuff.
this.interval = setInterval(() => {
this.counter++;
console.log("Counter = " + this.counter)
}, 1000);
console.log("Tab became active");
// Send a message to the background script:
sendMessage('content-script-loaded', 'arg1','arg2');
// You can do RPC with sendRequest
var result = await sendRequest('someRpcFunction', 1, 2);
// result will be 1+2 = 3
},
deactivate() {
// on deactivate you cleanup your stuff.
clearInterval(this.interval);
console.log("Tab became inactive");
}
}
var app = MyExtension({
messageHandlers: {
'content-script-loaded'(arg1, arg2) {
// MyContentScript sent us a message.
}
},
rpc: {
async someRpcFunction(arg1, arg2) {
return arg1 + arg2;
}
},
contentScripts: [
MyContentScript
],
});
Browser RPC
// Some background.js
var rpcServer = require('browser-extension-tools/browser-rpc').getServer()({
async myRpcFunction(arg1, arg2) {
return arg1 + arg2;
}
});
Some panel or extension page:
// page.js
var rpc = require('browser-extension-tools/browser-rpc').getClient();
await rpc('myRpcFunction', 1, 2); // -> 3