Skip to content

How to integrate the API of SingleFile into an extension

Gildas edited this page Feb 28, 2021 · 55 revisions
  1. Create a manifest.json file containing the content below. Copy the JavaScript files present in the manifest and lib/single-file/dist/single-file.js.
{
  ...
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "run_at": "document_start",
      "js": [
        "dist/chrome-browser-polyfill.js",
        "dist/single-file-frames.js"
      ],
      "all_frames": true,
      "match_about_blank": true
    }
  ],
  "background": {
    "scripts": [
      "extension/lib/single-file/core/bg/scripts.js",
      "extension/lib/single-file/fetch/bg/fetch.js",
      "extension/lib/single-file/frame-tree/bg/frame-tree.js",
      "extension/lib/single-file/lazy/bg/lazy-timeout.js"
    ],
    "persistent": false
  },
  "web_accessible_resources": [
    "dist/web/hooks/hooks-web.js",
    "dist/web/hooks/hooks-frames-web.js"
  ],
  "permissions": [
    "activeTab",
    "<all_urls>"
  ]
}
  1. Inject SingleFile in the tab to save by executing the code below in a background script.
await extension.injectScript(tabId, options);
  • arguments
    • tabId is the id of the Tab where to inject SingleFile
    • options is an object containing the options to pass to SingleFile. The default values can be found in the extension/core/bg/config.js file.
  • return
    • A promise which is resolved once SingleFile is injected
  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(options);
  • 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 dist/chrome-browser-polyfill.js scripts in the manifest.json file.
Clone this wiki locally