Skip to content

Instantly share code, notes, and snippets.

@naholyr
Last active December 5, 2023 23:37
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save naholyr/8657eb77e198e1b49c1d to your computer and use it in GitHub Desktop.
Save naholyr/8657eb77e198e1b49c1d to your computer and use it in GitHub Desktop.
Chrome extension exposing JS API

Install

Clone the repo and drop the folder into "chrome://extensions" page.

Use

Open any web page ("about:blank" will work too) and a console, then inspect and play with MY_API global variable.

Screenshot

(function (exports) {
exports.hello = function (who) {
document.dispatchEvent(new CustomEvent('MY_API:hello', {
detail: {
who: who || 'world'
}
}));
};
})(window.MY_API = {});
// Inject API to web page
var s = document.createElement('script');
s.src = chrome.extension.getURL('api.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
// Register event to allow dialog between page-wide and extension-wide code
document.addEventListener('MY_API:hello', function(e) {
alert('Hello, ' + e.detail.who);
// ↑ how to pass data
});
{
"manifest_version": 2,
"name": "Hello API",
"description": "Add JS API.",
"version": "1.1",
"web_accessible_resources": ["api.js"],
"content_scripts": [
{
"matches": ["*://*/*"],
"match_about_blank": true,
"js": ["hello.js"]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment