Search code examples
javascriptfirefoxchromiumwebpage-screenshot

Calling Firefox's :screenshot helper function in the Browser Console with JavaScript


I am trying to write a small script to copy in the web console of a live page, and part of what this script needs to do is take several screenshots of the document body. This script will be for personal use, for a very specific task, so I think it would not be a problem to use Firefox's built in helper function :screenshot, instead of a more cross-compatible solution.

I have read this question about the same topic, which explains why it is not possible to call such helper functions from the webpage's console in JavaScript. But what I thought I could do instead, is to use Firefox's browser console, which gives access to the entire browser. Again, I have been literaly just copying and pasting functions into the console to use while interacting with the page, so if I can call the :screenshot function programmatically from the browser console I would just need to figure out how to access the DOM of a particular document or tab and I will get the same result.

I have tried to import and use html2canvas, but it did not work most probably because the content that I am trying to screenshot resides inside a shadow-root. I know that one alternative is to write my own extension, but I would like to avoid such a job for this task. Eventually, do you know if it is possible to achieve similar results in a Chromium based browser (Brave)?

Thank you very much :D


Solution

  • The good news is that, yes, you can invoke the devtools screenshot functionality from the browser console. Conveniently the default selected node is the document body.

    (async()=>{
        const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm");
        const { gDevTools } = require("devtools/client/framework/devtools");
        const { TargetFactory } = require("devtools/client/framework/target");
        const target = await TargetFactory.forTab(gBrowser.selectedTab);
        const toolbox = await gDevTools.showToolbox(target, "inspector");
        const inspector = toolbox.getPanel("inspector");
        inspector.screenshotNode();
    })()
    

    Now the bad news. Accessing the DOM of content page from the browser console is unbearably tricky :(