How to access google chrome extension from any javascript page

I am trying to figure out how I can call my extension from a regular web page. All the documentation that I find is either for communication between extensions, or between content scripts and extensions.

Any pointers are much appreciated!

+4
source share
2 answers

I think you should make a content script that injects an object into your page that calls your extension.

Create a script content that injects YourExt.js into each page, which should contain:

var YourExt = { doThis: function () { chrome.extension.sendRequest('doThis'); }, doThat: function () { chrome.extension.sendRequest({ action: 'doThat', params: ['foo','bar'] }); } } 
+4
source

While extensions cannot access page variables and vice versa, you can communicate between the page and the extension through events. The following is a brief example of creating custom events:

 function fireEvent(name, target) { //Ready: create a generic event var evt = document.createEvent("Events") //Aim: initialize it to be the event we want evt.initEvent(name, true, true); //true for can bubble, true for cancelable //FIRE! target.dispatchEvent(evt); } function foobar() { alert("foobar"); } function testEvents() { window.addEventListener("foobar", foobar, false); //false to get it in bubble not capture. fireEvent("foobar", document); } 

(taken from here )

So, if you need to transfer information from a page to an extension, you will need to fire a custom event on the page that you will listen to in your script content.

+1
source

Source: https://habr.com/ru/post/1347745/


All Articles