Installations
npm install @andreadev/bg-script
Developer Guide
Typescript
No
Module System
ESM
Node Version
22.2.0
NPM Version
9.8.1
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
validate.email 🚀
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Developer
andreadev-it
Download Statistics
Total Downloads
3,633
Last Day
5
Last Week
7
Last Month
28
Last Year
552
GitHub Statistics
ISC License
2 Stars
53 Commits
1 Watchers
5 Branches
2 Contributors
Updated on Aug 20, 2024
Bundle Size
8.30 kB
Minified
2.80 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.2.0
Package Id
@andreadev/bg-script@1.2.0
Unpacked Size
90.36 kB
Size
18.05 kB
File Count
21
NPM Version
9.8.1
Node Version
22.2.0
Published on
Jun 27, 2024
Total Downloads
Cumulative downloads
Total Downloads
3,633
Last Day
0%
5
Compared to previous day
Last Week
250%
7
Compared to previous week
Last Month
-34.9%
28
Compared to previous month
Last Year
-38.7%
552
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
bg-script - Library for chrome extension communication
This library will help you communicate between your content scripts and the background script, offering an alternative to the default sendMessage
API.
The chrome API that do this is not very practical in the way it's layed out, and doesn't allow you to easily get response for asynchronous
actions.
This project was inspired by comlink, and it started out as a way for me to better understand Javascript Proxies.
How does it work?
Access background script methods from content script
In your background script, you must create a BackgroundHandler class and pass it an object that contains the properties and methods you want to share:
1// background.js 2 3function remoteFunction() { 4 return "Executed remotely"; 5} 6 7let bgHandler = new BackgroundHandler({ 8 remoteFunction // This is a shorthand for `remoteFunction: remoteFunction` 9});
In your content script, you should create a BackgroundScript class and then use it like this:
1var bgScript = new BackgroundScript("script-id"); 2 3// Use an async function for better code! 4async function foo() { 5 // Get a reference to the background script connection (which is a proxy) 6 let connection = await bgScript.getConnection(); 7 8 let result = await connection.remoteFunction(); 9 10 console.log(result); // --> "Executed remotely" 11} 12 13// Execute the function when needed 14foo();
Acess content scripts methods from the background script
You can call methods exposed from the content script in a similar way:
1// Content Script file 2 3function contentScriptMethod() { 4 return "Executed in the content script"; 5} 6 7var bgScript = new BackgroundScript("my-script" , { 8 contentScriptMethod 9});
If you have the tabId where the script resides, you can call its methods like this:
1// Background script file 2 3var bgHandler = new BackgroundHandler(); 4 5async function callScriptMethod(tabId) { 6 let connection = await bgHandler.getScriptConnection("my-script", tabId); 7 8 let result = await connection.contentScriptMethod(); 9 10 console.log(result); // --> Executed in the content script; 11} 12
Installation
Without bundler
Download the build/bgscript.js
file and include it in your chrome extension in the following two ways.
In order to use it in your content scripts, include it in your manifest.json as the first content script:
"content_scripts": [{
"js": ["bgscript.js", "my-content-script.js", ...]
}]
Similarly, for the background, you need to declare it as first script in the "background scripts" section of your manifest file:
"background": {
"scripts": [ "bgscript.js", "my-background-script.js"]
}
When you do this, the two classes will be automatically available in your scripts.
If you're building an html page for your extension, just add the following tag to the head of your page, before any other script.
1<script src='bgscript.js'></script>
With bundler
If you use a bundler, you can install the npm package:
npm install --save @andreadev/bg-script
Then, in your code, you can just import the class that you want to use:
1// Background script 2import { BackgroundHandler } from '@andreadev/bg-script'; 3 4// Content script 5import { BackgroundScript } from '@andreadev/bg-script';
How to use it
Get a variable from the background script
Background script:
1let shared = { 2 variable: 10 3} 4 5// This function shows how to use shared variables within the script to avoid problems with object references 6function setVariable(val) { 7 shared.variable = val; 8} 9 10// Initialize the Background script handler passing the object to be shared 11let bgHandler = new BackgroundHandler(shared);
Content script:
1// Initialize the background script object 2let bgScript = new BackgroundScript(); 3 4async function foo() { 5 // Get a connection to the background script 6 let connection = await bgScript.getConnection(); 7 8 // Get the variable from the background script 9 let variable = await connection.variable; 10 11 console.log(variable); 12} 13 14foo();
Execute a method from the background script
Background script:
1var variable = null; 2 3function setVariable(val) { 4 variable = val; 5} 6 7function showVariable() { 8 return variable; 9} 10 11let shared = { 12 setVariable, 13 showVariable 14} 15 16// Initialize the Background script handler passing the object to be shared 17let bgHandler = new BackgroundHandler(shared);
Content Script:
1let bgScript = new BackgroundScript(); 2 3async function foo() { 4 let connection = await bgScript.getConnection(); 5 6 await connection.setVariable("Hello world"); 7 8 let variable = await connection.showVariable(); 9 10 console.log(variable); 11} 12 13foo();
Shortcut for setting a shared variable
Instead of creating a setter function and using it like I showed in the examples above, if the variable you want to change is shared, you can do it this way:
Background script:
1let shared = { 2 variable: null 3} 4 5let bgHandler = new BackgroundHandler(shared);
Content script:
1let bgScript = new BackgroundScript(); 2 3async function foo() { 4 let connection = await bgScript.getConnection(); 5 6 // Set the variable. The brackets are there to avoid syntax errors. 7 await (connection.variable = "Hello world"); 8 9 // Show the new variable value 10 console.log(await connection.variable); 11} 12 13foo();
Note that when you set a variable, the new value will be returned (just like when you set a normal variable). This means that doing it this way will give you the same result as before:
1 ... 2 // Set the variable and log its new value 3 console.log(await (connection.variable = "Hello world")); 4 ...
Communicate with the content scripts
From version 1.1.0, you can do all the aforementioned actions from the background script too!
By default, the scripts are associated with their tab ids. For this reason, you should first know which tab you want to communicate with. If you have this tab id in a variable called "tabId", then you can do the following:
1// Background script 2var bgHandler = new BackgroundHandler(); 3 4// ... 5 6async function callContentScript(tabId) { 7 let connection = await bgHandler.getScriptConnection("script-id", tabId); 8 await connection.remoteMethod(); // This method resides in the content script. 9}
The first variable for the getScriptConnection
method is the script ID. This must be set in the content script when a new BackgroundScript
class is created:
1// Content script 2 3var bgScript = new BackgroundScript("script-id", { 4 remoteMethod 5}); 6 7function remoteMethod() { 8 return "Method in the content script"; 9}
API Reference
BackgroundHandler class
Class creation:
1var bgHandler = new BackgroundHandler( [exposed-data], [options] );
Parameters:
Parameter | Description |
---|---|
[exposed-data] | Object (optional) - An object containing all the properties and methods that will be exposed to the content scripts. This are the limitations: do not put a property (or method) called "then" or "$getMyTabId", because they will be rejected. Also, if you expose a property, it must be JSON-friendly to be correctly received by other scripts. All exposed methods should also return JSON-friendly values in order to work correctly. |
[options] | Object (optional) - An object that will enable further customization. |
[options.errorCallback] | function - A callback that will be fired whenever there is an error in the background handler. It will get passed an object with some details of the error: an errorId and an error (the error description). |
Events:
Name | Details | Description |
---|---|---|
connectionreceived | { scriptId, tabId } | This event fires when a script has successfully connected to the background handler. |
connectionended | { scriptId, tabId } | This event fires when a script has succesfully disconnected from the background handler. |
In this page you can find more information about the connection lifecycle.
BackgroundScript class
Class creation:
1var bgScript = new BackgroundScript( [script-id], [exposed-data], [options] );
Parameters:
Parameter | Description |
---|---|
[script-id] | String (optional) - A unique ID for this script. By default, this id will be tab-specific, so that you can have multiple tabs with the same script using the same script id. If omitted, a unique id will be generated |
[exposed-data] | Object (optional) - An object containing all the properties and methods that will be exposed to the Background script. You can put almost everything here, but just avoid to insert a "then" method, because it will be ignored. Also remember that if you want to directly get a remote property, it must be JSON-friendly, so don't insert properties that cannot be converted to JSON. |
[options] | Object (optional) - An object with some options to customize how the script work |
[options.context] | String - One of "content" (default), "devtools" and "tab-agnostic". If the value is "content", the script id will be associated with the current tab id. If you want to use this library from a devtools script, then you must set this option to "devtools" to automatically associate the script id with the inspected tab id. If the value is "tab-agnostic" the script id won't be associated to any tab id, so you won't be able to create another connection with the same script id. |
Events:
Name | Description |
---|---|
connected | The script has succesfully connected to the background handler. Since the first connection is done when you create the class instance, this event will only fire for the following connections and not for the first one. |
disconnected | The script has succesfully disconnected from the background handler. |
Connection proxy
Get a connection to the background script:
1// Content script
2let bgScript = new BackgroundScript("script-id");
3//...
4let connection = await bgScript.getConnection();
Get a connection to a content script:
1// Background script
2let bgHandler = new BackgroundHandler();
3// ...
4let connection = await bgHandler.getScriptConnection("script-id", tabId);
Also, if you're in a content script, you can retrieve your tabId by calling this method:
1let connection = await bgScript.getConnection(); 2 3let tabId = await connection.$getMyTabId();
Using the sendMessage API alongside this library
From version 1.2.0, there is a very small limitation on how to use the "sendMessage" API, even though this library mostly uses ports. Just avoid having a message that is an object, with a type
property that starts with "bgscript".

No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: ISC License: LICENSE:0
Reason
9 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-434g-2637-qmqr
- Warn: Project is vulnerable to: GHSA-49q7-c7j4-3p7m
- Warn: Project is vulnerable to: GHSA-977x-g7h5-7qgw
- Warn: Project is vulnerable to: GHSA-f7q4-pwc6-w24p
- Warn: Project is vulnerable to: GHSA-fc9h-whq2-v747
- Warn: Project is vulnerable to: GHSA-vjh7-7g9h-fjfh
- Warn: Project is vulnerable to: GHSA-4gmj-3p3h-gm8h
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
Reason
Found 1/29 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 2 are checked with a SAST tool
Score
1.9
/10
Last Scanned on 2025-02-24
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More