Search code examples
javascriptgoogle-chrome-extension

Unable to document.write after stop()


I'm writing a Chrome extension, which creates a new tab then inject a script to overwrite the whole HTML of it. (a bit of the background can refer to another post: Chrome extension service worker inject script to new about:blank tab). Here is the script:

let openedTab = await chrome.tabs.create({active: false, url: randomURL});

openedTabID = openedTab.id;
                    
let writeHTML = function (strHTML) {
    stop();
    //document.open();
    document.write(strHTML)
    //document.close();
}
chrome.scripting.executeScript({target : {tabId : openedTabID}, func : writeHTML, injectImmediately: true, args: [newTabHTML[0].result]});

I find that the strHTML cannot be written to it sucessfully, the page keeps in blank (blank due to loading stopped), unless I don't stop() the loading of the page. If I don't stop() it, the strHTML can overwrite the page, but just the tab icon keeps circling around (loading). I find that quite annoying and I afraid that the original page (the url: randomURL) will eventually be loaded and affect my intended actions afterwards. So I want to ask how I can trully stop the loading of the page before I write my HTML to it?

Here is some troubleshooting I tried......

I tried to manually put document.write("asdasd") into the console, no observed change but only return undefined but no error too.

I tried to manually enter asdasadasdsd between the loaded html tag, also no observed change. Seems like the display is not linked with the html code if I stop() the page.

I'm not very sure whether this is due to the original page is an angularJS page, as if I stop() the loading immediately I inject the script, the HTML loaded is

<html ng-app="ansd" ng-controller="ApplicationController as AppCtrl"></html>

But I can document.write("asdasd") to overwrite the page if I enter into console after the page is loaded.

And even I put document.documentElement.remove(); to remove the whole HTML (yes, removed successfully) after stop() , I still cannot document.write("asdasd").

Is this due to the javascript problem or it's Chrome's problem, or it's my problem? Please help. Thank you very much.


Solution

  • Delaying stop seems to work:

    let writeHTML = function (strHTML) {
        setTimeout(stop);
        document.write(strHTML)
    }
    

    A more reliable workaround might be to open a tab with url: 'foo.html' where foo.html is a page in your extension, which will then modify itself using data from the background script.