104

I have a chrome extension. I need to analyse from the HTML source of the current page. I found here all kinds of solutions with background pages and content scripts but none helped me. here is what I have so far:

manifest.json

{
  "name": "Extension",
  "version": "1.0",
  "description": "Extension",
  "browser_action": {
    "default_icon": "bmarkred.ico",
    "popup": "Test.html"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["content.js"]
    }
  ],
  "background": {
    "page": "backgroundPage.html"
  },
  "permissions": [
    "cookies",
    "tabs",
    "http://*/*", 
    "https://*/*"
  ]
}

background.html

<html>
<head>
<script type="text/javascript">
    try {
        chrome.tabs.getSelected(null, function (tab) {
            chrome.tabs.sendRequest(tab.id, {action: "getSource"}, function(source) {
                alert(source);
            });
        });
    }
    catch (ex) {
        alert(ex);
    }
</script>
</head>
</html>

content.js

chrome.extension.onRequest.addListener(function(request, sender, callback) {
    if (request.action == "getSource") {
        callback(document.getElementsByTagName('html')[0].innerHTML);
    }
});

The alert always alerts undefined. even if i change in the content.js file the callback function to:

callback('hello'); 

still the same result. What am I doing wrong? maybe I'm going at this the wrong way. What I really need is this: When the user opens the extension popup (and only then), I need HTML of the current page so I can analyse it.

3
  • A problem is that the code in your background page is run immediately (before the content scripts are injected). A very similar/duplicate question has been asked before; Have a look at the answer at Open a new Google Chrome tab and get the source.
    – Rob W
    Commented Jul 27, 2012 at 10:06
  • Thanks for your reply rob. i copied the code segments in your attached link but it still doesn't work. The problem is that my extension is a popup and i need to get the HTML only when the user opens my extension. for example, if the current tab is facebook.com then only when i open my extension, i will retrieve the html source to my js file (not the content script or the background page).
    – Mr T.
    Commented Jul 27, 2012 at 17:50
  • Update your question with your current code. The code has to contain comments which highlight the problem.
    – Rob W
    Commented Jul 27, 2012 at 19:46

2 Answers 2

176

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;
}
17
  • @Gil Tankus So sorry for my first post, didn't pay enough attention to the comments (again) and ended up just regurgitating what Rob W said. The new post should have what you wanted.
    – PAEz
    Commented Jul 28, 2012 at 12:38
  • Thanks, your answer was really helpful, my problem is that the on onMessage happens asynchronous. in my popup, i have all sorts of other stuff that relay on the source HTML. how can i save the source in a global var and only then continue with the page onload function?
    – Mr T.
    Commented Jul 28, 2012 at 18:47
  • I don't think you can. Your either going to have to put it in the callbacks code or in a function and call that in the callback...if only JS had a goto command aye? ;P
    – PAEz
    Commented Jul 28, 2012 at 18:57
  • 27
    Why not just something like document.documentElement.outerHTML instead of the DOMtoString function?
    – djfm
    Commented Jan 3, 2015 at 11:24
  • 2
    This answer works by re-generating the page source from the DOM (which could be altered by other scripts at runtime), it doesn't return the raw HTML response from the server.
    – Dai
    Commented Jun 18, 2016 at 1:05
2

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });
1
  • Have you tried this method (and submit the app to Webstore) before? It's almost like a hack of using content_scripts without using it. Commented Jun 13, 2021 at 1:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.