Search code examples
google-chrome-extension

Error handling response: ReferenceError: document is not defined


I was trying to learn how to do a dummy Chrome extension, and I got that error in the title. This extension would try to remove all images from Google Images and do other things I am not sure yet, like redirecting or just playing, but I can't find a solution to this error.

chrome.tabs.onActivated.addListener(function () {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            this.callOnPage(tabs[0].url);
        });
    });
    
    chrome.tabs.onUpdated.addListener(
        function (tabId, changeInfo, tab) {
            callOnPage(tab.url);
        }
    );
    
    var callOnPage = (function (activeTab) { 
        var googleImages = activeTab.indexOf('google.com') !== -1 && activeTab.indexOf('tbm=isch') !== -1;
        var googleVideos = activeTab.indexOf('google.com') !== -1 && activeTab.indexOf('tbm=vid') !== -1;
    
        console.log(`images: ${googleImages}, videos: ${googleVideos}`);
    
        var images = document.getElementsByTagName('img');
        var l = images.length;
        for (var i = 0; i < l; i++) {
            images[0].parentNode.removeChild(images[0]);
        }
    })

manifest

    {
        "name": "Google Image Blocker",
        "manifest_version": 3,
        "version": "1.0",
        "background": {
            "service_worker": "googleImageBlocker.js"
        },
        "permissions": [
            "tabs"
        ],
        "externally_connectable": {
            "matches": ["*://*.google.com/*"]
        }
    }

Solution

  • document in this line of code:

    var images = document.getElementsByTagName('img');  
    

    refears to your service_worker. If you want to remove images from google pages you have to use content script.
    Take a look at this and this