0

This is my manifest.json:

{
  "manifest_version":2,
  "name": "Name",
  "description": "Description",
  "version":"1.0",
  "browser_action":
  {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "permissions": [
    "tabs"
  ]
}

Here is my background.js:

chrome.tabs.onUpdated.addListener( (tabId, changeInfo, tab) => {
  if (typeof changeInfo.url !== "undefined" && changeInfo.url.startsWith("chrome://newtab/") === false){
    alert(changeInfo.url);
    //somehow get the HTML of the page given tabId and store as string
}
});

It will be greatly appreciated if someone can help me out here. As I specified before, I need the exact HTML of the page as the user sees it.

1 Answers1

0

Add the sites you want to be able to read (or all sites "*://*/*") to permissions in manifest.json, then use chrome.tabs.executeScript to extract its HTML as a string.

  • DOM elements or class objects like Map can't be extracted. Only JSON-compatible types such as strings, numbers, boolean, null and array/objects of these types can be extracted.

  • The popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu to see console.log messages.

chrome.tabs.onUpdated.addListener(async (tabId, info, tab) => {
  if (info.url && !info.url.startsWith('chrome')) {
    const html = await getHtml(tabId);
    console.log(html);
  }
});

function getHtml(tabId) {
  return new Promise((resolve, reject) => {
    chrome.tabs.executeScript(tabId, {
      code: 'document.documentElement.outerHTML',
    }, results =>
      chrome.runtime.lastError
        ? reject(new Error(chrome.runtime.lastError.message))
        : resolve(results[0]));
  });
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • I tried doing that, but `document.documentElement.outerHTML` is returning something starting with ` – IEmpire Nov 22 '20 at 19:49
  • That's the correct result because doctype isn't part of DOM. You can add it explicitly if you need it, see [this answer](https://stackoverflow.com/a/11696154). – wOxxOm Nov 22 '20 at 19:55