Skip to content

How to integrate the API of SingleFile into an extension

Gildas edited this page Jun 15, 2022 · 55 revisions
  1. Create a manifest.json file containing the content below. Copy the JavaScript files from the lib folder present in the manifest.
{
  ...
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "run_at": "document_start",
      "js": [
        "lib/chrome-browser-polyfill.js",
        "lib/single-file-frames.js",
        "lib/single-file-extension-frames.js"
      ],
      "all_frames": true,
      "match_about_blank": true
    },
    {
      "matches": [
        "<all_urls>"
      ],
      "run_at": "document_start",
      "js": [
        "lib/chrome-browser-polyfill.js",
        "lib/single-file-bootstrap.js",
        "lib/single-file-extension-core.js",
        "lib/single-file.js"
      ],
      "all_frames": false
    }
  ],
  "background": {
    "page": "background.html",
    "persistent": false
  },
  "web_accessible_resources": [
    "lib/single-file-hooks-frames.js"
  ],
  "permissions": [
    "activeTab",
    "<all_urls>"
  ]
}
  1. Create a background.html file or insert in your background page the scripts below.
<script src="/lib/chrome-browser-polyfill.js"></script>
<script src="/lib/single-file-background.js"></script>
  1. Capture the page by executing the code below in the content script of the tab where SingleFile has been injected.
const { content, title, filename } = await extension.getPageData({
  removeHiddenElements: true,
  removeUnusedStyles: true,
  removeUnusedFonts: true,
  removeImports: true,
  blockScripts: true,
  blockAudios: true,
  blockVideos: true,
  compressHTML: true,
  removeAlternativeFonts: true,
  removeAlternativeMedias: true,
  removeAlternativeImages: true,
  groupDuplicateImages: true
});
  • arguments
    • options is an object containing the options to pass to SingleFile.
  • return
    • A promise which is resolved to an object containing the following properties:
      • content: HTML content of the page
      • title: tile of the page
      • filename: filename (if the option filenameTemplate is defined)
  1. Notes
  • If your project already includes a polyfill of the API for WebExtensions for Chromium-based browsers then you can omit the lib/chrome-browser-polyfill.js scripts in the manifest.json file.