t Chrome Extension Reference

By pjain      Published July 9, 2020, 7:12 p.m. in blog AI-Analytics-Data   

Chrome Dev Ref

Basic Development Path

  1. Create a directory with following files - this "package" directory is what is zipped and inserted as a crx file

  2. You need a manifest describing contents of your extension

    • has metadata about your extension such as name, version, etc.,
    • connects the popup browser action to a local in directory file
    • Commands - tie keyboard actions to click on icon - when not showing
  3. html - for the popup that appears

  4. hello_extensions.png - an image used to show on bar

Installing on your local

  1. Manual Install of the "unpacked" extension directory by

    • click on : three dots on top right of Chrome browser
    • Go to more tools > Extensions Page
    • Click on Load Unpacked extensions, point it to the directory you created above
  2. Latest chrome browser PROBLEM - icon was not showing

    • Used to be you would resize the address bar
    • Now there is a "puzzle piece" icon at very end of the extensions panel (to right of address bar)
    • If you right click on it, all "enabled" extensions are shown
    • To allow your extension to be shown always, click the pin icon there
  3. Debugging, Reloading after Modifying Extension code

    • After making changes, click Reload on this extension on this page to see changes

To pack for distribution:

Visit chrome://extensions/ on the chrome browser
Click "Pack extension" to create a .crx file. Keep the .key file handy to make changes to the .crx
Distribute this .crx file

Resources

http://developer.chrome.com/extensions

Concept, What

  • Chrome is closer to mobile Web! https://developer.chrome.com/extensions/getstarted.html

  • What a Chrome extension is and how Chrome extensions work.

    • just some HTML, CSS and JavaScript that allows you to add some functionality to Chrome through some of the JavaScript APIs Chrome exposes. An extension is basically just a web page that is hosted within Chrome and can access some additional APIs.

    EX: Browser Action extension. This kind of extension puts a button in the Chrome toolbar that will show an HTML page when clicked and optionally execute some JavaScript.

Limited to specific Pages

> Chrome extensions can also be created to work only on certain pages through the use of Page Actions, they can run code in the background using Background Pages, and they can even modify an existing page loaded in the browser using Content Scripts.

How it works

  1. INJECT JS into specified page

  2. Extensions currently have very Greasemonkey-like functionality: you identify which web pages should be modified, plus JavaScript to be added to those pages.

  3. By default, the extension’s JavaScript runs after the page loads, but you can specify that the extension’s JavaScript should run before the page loads.

Limitations

  • Right now, you can only load one JS file

  • You cannot inject SCSS

  • Chrome has limited support for internationalization, which is one of the benefits of Firefox’s more comprehensive way of packaging up plugins.

  • Another limitation of the current Chrome extension spec is that you can’t do much other than modify pages via JavaScript. And I didn’t see a way to introduce new widgets into the actual “chrome” of the Chrome browser.

Content Scripts

101 - Why, References

When I access the document.body.insertBefore method from within popup.html it overlays the

on the popup, rather than the current webpage. https://developer.chrome.com/extensions/content_scripts

This is because, extension pages and the JS scripts that run in them, eg as the browser_action popup or background script have their own DOM, document, window, and a chrome-extension:// URL.

You need a content script to access DOM of web pages and interact with a tab's contents. Content scripts will execute in the tab as a part of that page, not as a part of the extension.

Method 1. Declarative

// manifest.json:
"content_scripts": [{
  "matches": ["*://*.example.com/*"],
  "js": ["contentScript.js"]
}],

Here the contentScript.js script will run once when the page loads. After that happens, use messaging but note, it can't send DOM elements, Map, Set, ArrayBuffer, classes, functions, and so on - it can only send JSON-compatible simple objects and types so you'll need to manually extract the required data and pass it as a simple array or object.

Method 2. Programmatic

Use chrome.tabs.executeScript to inject a content script on demand. The callback of this method receives results of the last expression in the content script so it can be used to extract data which must be JSON-compatible, see method 1 note above.

Required permissions in manifest.json:

  • Best case: "activeTab", suitable for a response to user action like a click. Doesn't require any permissions when installing the extension.
  • Usual: "://.example.com/" plus any other sites you want.
  • Worst case: "" or ":///", "http:///", "https:///" - when submitting into Chrome Web Store all of these put your extension in a super slow review queue because of broad host permissions.

As an example of the second method, let's add that div when a browser action is clicked. We'll use chrome.tabs.executeScript() in the browserAction click handler to inject a content script as a file or a literal code string if it's small.

Simple call example

chrome.tabs.executeScript({ code: `(${ inContent })()` });
function inContent() {
  const el = document.body.appendChild(document.createElement('div'));
  el.style.cssText = 'position:fixed; top:0; left:0; right:0; background:red';
  el.textContent = 'DIV';
}

Calling with parameters and receiving a response:

This example uses automatic conversion of inContent function's code to string, the benefit here is that IDE can apply syntax highlight and linting. The obvious drawback is that the browser wastes time to parse the code, but usually it's less than 1 millisecond thus negligible.

chrome.tabs.executeScript({
  code: `(${ inContent })(${ JSON.stringify({ foo: 'bar' }) })`
}, ([result] = []) => {
  if (!chrome.runtime.lastError) {
    console.log(result); // shown in devtools of the popup window
  }
});
function inContent(params) {
  document.body.insertAdjacentHTML('beforeend',
    `<div style="
      all:unset;
      position:fixed;
      top:0; left:0; right:0; bottom:0;
      background-color:rgba(0,255,0,0.3)"
    >${params.foo}</div>`);
  return {
    success: true,
    html: document.body.innerHTML,
  };
}
  • SRC https://stackoverflow.com/a/4532567

Publishing

Publishing your Extension

  1. Your plugin has to have a unique identifier (40 digit hexadecimal number). Given an identifier such as “00123456789ABCDEF0123456789ABCDEF0123456”, an extension can include an image such as foo.gif and then easily access that image by using a full path such as “chrome-extension://00123456789ABCDEF0123456789ABCDEF0123456/foo.gif”

  2. You need a manifest describing contents of your extension

– The “content script” (the JavaScript of an extension) gets its own global scope separate from the web page, so you don’t need to worry about global variables conflicting. But you can still get access to the web page’s global variables using the “contentWindow” variable.

– Bundling your extension directory into a CRX file (http://src.chromium.org/viewvc/chrome/trunk/src/chrome/tools/extensions/chromium_extension.py?content-type=text/plain) “.crx” Chrome Extension file is as simple as running a short Python script.(http://src.chromium.org/viewvc/chrome/trunk/src/chrome/tools/extensions/chromium_extension.py?content-type=text/plain)

Manifest

  • You need a manifest describing contents of your extension

= has metadata about your extension such as name, version, etc., - looks much simpler to me than how Firefox wants extensions to be packaged.

Portable Extension development - dev for MDN NPAPI

– Chrome also supports binary NPAPI (Netscape Plugin Application Programming Interface) plugins.

Internationalization

  • Chrome has limited support for internationalization, which is one of the benefits of Firefox’s more comprehensive way of packaging up plugins.

Testing, Productionizing

Reverse Engineering

How to inspect source code of chrome extension

Testing tools

  • coveo-labs/web-scraper-helper: A tool to test web scraping rules.
    • https://chrome.google.com/webstore/detail/web-scraper-helper-for-co/demelhhhnkocnphihjbhpafjnknknkdf?hl=en-US

      Coveo Cloud V2 Web and Sitemap source types can use a web scraping configuration to exclude web page sections, extract metadata, and create sub-items for web pages to index (see Web Scraping Configuration). The web-scraper-helper works directly in your browser allowing you to easily create and test your web scraping configuration when visiting web site pages requiring web scraping.

Security - Extensions ARE INSECURE

Extensions can send ALL page data to BE servers

  • pedrouid/chrome-extension-browser-data: Demo Chrome Extension to scrape all browser data from a user

    A demo chrome extension that scrapes all browser data from any website and sends it to a server. This example Chrome Extension has the same permissions as popular extensions such as AdBlock and Pocket. This demontrastes how vulnerable browsers are right now to browser extensions without access to an user-encrypted local storage. Something similar to Apple Keychain or Android Keystore available as native API by the browser would prevent this easily.

In-Browser Debugging

Chrome browser ..

Functions to help in debugging

Since JSON.stringfy doesnt work in all browsers debug .. do

> window.DumpObjectIndented =
function DumpObjectIndented(obj, indent)
{
  var result = "";
  if (indent == null) indent = "";

  for (var property in obj)  {
    var value = obj[property];
    if (typeof value == 'string')
      value = "'" + value + "'";
    else if (typeof value == 'object')     {
      if (value instanceof Array)    {
        // Just let JS convert the Array to a string!
        value = "[ " + value + " ]";
      }  else  {   // Recursive dump
        // (replace "  " by "\t" or something else if you prefer)
        var od = DumpObjectIndented(value, indent + "  ");
        // If you like { on the same line as the key
        //value = "{\n" + od + "\n" + indent + "}";
        // If you prefer { and } to be aligned
        value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
      }
    }
    result += indent + "'" + property + "' : " + value + ",\n";
  }
  return result.replace(/,\n$/, "");
}

window.DumpObjectIndented(OBJYOU WANT TO PRINT)

0 comments

There are no comments yet

Add new comment

Similar posts

Time series Analysis and Prediction

Apple Mac Mini

b Use of BrowserWare

t Firefox Extensions