lith
lith

Reputation: 949

Firefox webextension: Save page as html or text

With the new firefox webextensions: Is there a way to save the current page (or a part of it) as html (or text) to disk? If not, how are the chances, such an API will be implemented in the future?

I didn't find any suitable API and appreciate any help.

Regards

Upvotes: 1

Views: 2208

Answers (1)

Cam U
Cam U

Reputation: 340

There are probably several ways to do this. The following will get you started. It saves the webpage in the currently focused tab in the active window to the browser's default downloads path. The file name is set to 'samplePage.html' (you can change that by modifying the filename value in the downloads.download() options; or you can remove that field entirely and leave it to the default naming).

You will need to store icon images in your webextension package for the user to be able to click on. Also, be sure to navigate to a webpage you want to save before you try to use the webextension; webextensions are not active on the Firefox about:debugging page.

manifest:

{
  "name": "SavePage",
  "version":  "1.0",
  "description":  "Clicking browser icon saves page html",
  "manifest_version": 2,

  "icons": {
    "48": "icons/clickme-48.png"
  },

  "permissions": [
    "tabs",
    "activeTab",
    "downloads"
  ],

  "browser_action": {
    "default_icon": "icons/clickme-32.png"
  },

  "background": {
    "scripts": ["background.js"]
  }       
}

background script:

/* BACKGROUND SCRIPT

Clicking on browser toolbar button saves the webpage in the
current tab to the browser's default downloads path with a
filename of "samplePage.html". The "tabs" and "downloads" 
permissions are required.

*/


browser.browserAction.onClicked.addListener((tab) => {
  var currentUrl = tab.url;

  function onStartedDownload(id) {
    console.log(`Started to download: ${id}`);
  }

  function onFailed(error) {
    console.log(`Something stinks: ${error}`);
  } 

  var startDownload = browser.downloads.download({
    url : currentUrl,
    filename: 'samplePage.html'
  });

  startDownload.then(onStartedDownload, onFailed);
});

An alternative approach might be to try to save the webpage to local storage rather than to disk. I have not explored that option.

These pages may be helpful:

downloads.download()

browserAction.onClicked

There may be security risks in giving a webextension these permissions. You will have to weigh the risks for your own usage pattern.

Upvotes: 1

Related Questions