Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup….

manifest.json

{
    "name": "Get pages source",
    "version": "1.1",
    "manifest_version": 3,
    "description": "Get active tabs or element on that pages source from a popup",

    "action": {
        "default_title": "Get pages source",
        "default_popup": "popup.html"
    },

    "permissions": [
        "scripting",
        "activeTab"
    ]
}

popup.html

function onWindowLoad() {
    var message = document.querySelector('#message');

    chrome.tabs.query({ active: true, currentWindow: true }).then(function (tabs) {
        var activeTab = tabs[0];
        var activeTabId = activeTab.id;

        return chrome.scripting.executeScript({
            target: { tabId: activeTabId },
            // injectImmediately: true,  // uncomment this to make it execute straight away, other wise it will wait for document_idle
            func: DOMtoString,
            // args: ['body']  // you can use this to target what element to get the html for
        });

    }).then(function (results) {
        message.innerText = results[0].result;
    }).catch(function (error) {
        message.innerText="There was an error injecting script : \n" + error.message;
    });
}

window.onload = onWindowLoad;

function DOMtoString(selector) {
    if (selector) {
        selector = document.querySelector(selector);
        if (!selector) return "ERROR: querySelector failed to find node"
    } else {
        selector = document.documentElement;
    }
    return selector.outerHTML;
}

Leave a Comment