0

I'm trying to create a Chrome extension, so that I can read it's content when a page is loaded.

document.addEventListener("DOMContentLoaded", function(){ 
    function modifyDOM() {
        return "<html>\n".concat(String(document.body.innerHTML),"\n</html>");
    }
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' 
    }, (results) => {
        let dat=String(results[0]);
        console.log(dat);
    });

 });

But it gives me error saying :

Unchecked runtime.lastError: Cannot access a chrome:// URL

_generated_background_page.html:1 Error handling response: TypeError: Cannot read property '0' of undefined

But the code works fine, when I put the code inside :

chrome.browserAction.onClicked.addListener(function(tab) {
 //this works only when I click on that extension icon
 ...

});

How can I resolve this ?

My code works when I click the button, but I wanted to check for page content change, as I couldn't find any API for that, I tried to do at-least when the page loads.

Danial
  • 542
  • 2
  • 9
  • 24
  • 1
    The error says you're running this code on a page with `chrome://` URL, probably the default empty new tab page. Don't do that. Only web pages are supported by executeScript. To suppress the error simply check chrome.runtime.lastError inside the callback, [example](https://stackoverflow.com/a/4532567). – wOxxOm Jul 07 '20 at 17:29
  • @wOxxOm thanks... that's something more than i want... really appreciate it.. – Danial Jul 10 '20 at 08:06

1 Answers1

1

Since I cannot comment on other posts yet I had to write this in an answer,

check the answer to this question chrome.tabs.executeScript: Cannot access a chrome:// URL

Here's what was said:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    //code in here will run every time a user goes onto a new tab, so you can insert your scripts into every new tab
});
Jazib Dawre
  • 64
  • 3
  • 4
  • 2
    Might be worth mentioning, `//code in here` should be chrome.tabs.executeScript(tabId, ..... – wOxxOm Jul 07 '20 at 17:28