leira
11/8/2015 - 10:03 AM

Chrome extension exposing JS API

Chrome extension exposing JS API

{
  "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"]
    }
  ]
}
// 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
});
(function (exports) {

  exports.hello = function (who) {
    document.dispatchEvent(new CustomEvent('MY_API:hello', {
      detail: {
        who: who || 'world'
      }
    }));
  };

})(window.MY_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.