ksol
ksol

Reputation: 12235

Trigger/invoke a Chrome extension from a web page

For the project I'm currently working on, I need to know if it is possible to invoke a Chrome extension.

I.e., clicking on a button (or a link) on my page would call the "Read It" extension, something like that.

Upvotes: 19

Views: 24433

Answers (4)

Bob
Bob

Reputation: 5618

Yes, it's possible. You could write a so-called Content Script to alter the page and hook event handlers to the links or buttons.

Upvotes: 1

Altanai
Altanai

Reputation: 1393

create a manifest with background.js and content.js . Use

chrome.tabs.sendMessage(tabId, {}, function() { ... });

in background to send messages to content script which is injected into every webpage that is opened when extension is installed and enabled . On the content.js script use

chrome.runtime.onMessage.addListener(function(req, sender, callback) {  
    // here use condition to find out when this extension's popup.html should be opened
    // and call the callback function which was passed in the argument list initially
    callback("something");
});

Here the callback function defines in background.js and passed to content.js is the code for opening a new extension window such as

var panel_props = {
            type: 'panel',
            'width': width,
            'height': height,
            'left': left,
            'top': top,
            url: "chrome-extension://" + <extensionid>+ "/index.html"   
          }

          chrome.windows.create(panel_props ,function (newWindow) { 
              vid = newWindow.id;
          });

Upvotes: 2

Miner_Glitch
Miner_Glitch

Reputation: 536

  1. Make a "fake" ajax call in your web page code.
  2. Intercept it in your extension (see https://medium.com/@gilfink/adding-web-interception-abilities-to-your-chrome-extension-fb42366df425)
  3. In the intercept, cancel the "fake" call and implement your desired behaviour.

Upvotes: 1

osoner
osoner

Reputation: 2415

You can inject your content-script to every page (register it in extension manifest) and alter the page html to add your button or a with your custom id.

The execution environment example explains it pretty good how you will trigger an event from the page to your content script. After you manage the trigger you can do anything you want as the extension logic.

Also keep in mind that this will require your extension's content-script to be injected to every page the user visits. It is not possible to actually trigger the execution of your content-script from the page if thats what you were asking.

Upvotes: 4

Related Questions