Skip to content

code description

Florent Daligand edited this page Apr 24, 2017 · 7 revisions

Code description

Define the main algo of the monBonCoin web extenstion


Background script

From Dev Mozilla

Background scripts are loaded as soon as the extension is loaded and stay loaded until the extension is disabled or uninstalled. You can use any of the WebExtension APIs in the script, as long as you have requested the necessary permissions.

Use in this webExtension to give access to Browser Action, as hide of add it authorized only if dedicated button in browser toolbar has been cliked. Related Doc

BrowserAction implementation

Deprecated since use of PageAction. Google doc says : Don't use browser actions for features that make sense for only a few pages. Use page actions instead.

chrome.browserAction.onClicked.addListener(parsePage);

browserAction.onClicked

Call parsePage when user click on the monBonCoin button on the browser toolbar.

Hint

browserAction.onClicked send a tab object ( tabs.Tab ) to the callback.

PageAction implementation

Chrome way

The implementation of pageAction is as explain in documentation. Nevertheless, one point not clearly mentionned in the documentation is that, if you want to use PageStateMatcher, you need to add permission for declarativeContent in the manifest.json

// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
  // Replace all rules ...
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    // With a new rule ...
    chrome.declarativeContent.onPageChanged.addRules([
      {
        // That fires when a page's URL contains a 'g' ...
        conditions: [
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { urlContains: 'leboncoin' },
          })
        ],
        // And shows the extension's page action.
        actions: [ new chrome.declarativeContent.ShowPageAction() ]
      }
    ]);
  });
});

Mozilla way

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (tab.url.match(/.*.leboncoin.fr.*/))
    {
        chrome.pageAction.show(tab.id);
    }
});

Messaging to content script

Extract from parsPage()

chrome.tabs.sendMessage(tab.id,"button pressed");

Sends a single message to the content script(s) in the specified tab.


Content script

Mozilla Doc

injectHideActionScript

Tips and Tricks

Clone this wiki locally