0

I'm developing a Chrome Extension (don't have a lot experience with it), and I've the following code:

window.onload = function () {
    validateCNPJ();
};

function validateCNPJ() {
    document.querySelector('div[data-field-name="CNPJ"] > input').addEventListener('keydown', (bla) => {
        let ble = bla.target.value;
        console.log(ble.length)
        if (ble.length > 17) {
            bla.preventDefault()
            bla.stopPropagation()
            return
        }

        ble = ble.replace(/\D/g, "")
        ble = ble.replace(/^(\d{2})(\d)/, "$1.$2")
        ble = ble.replace(/^(\d{2}).(\d{3})(\d)/, "$1.$2.$3")
        ble = ble.replace(/.(\d{3})(\d)/, ".$1/$2")
        ble = ble.replace(/(\d{4})(\d)/, "$1-$2")
        bla.target.value = ble;
    })
}

I added window.load so that when the page loads, the validateCNPJ function is activated. That function validates a specific field in a form in real time.

The issue is that when I upload the extension it shows a error message saying:

Uncaught ReferenceError: window is not defined

I tested the code inside the function validateCPNJ in the console of the browser and it worked normally.

The manifest file is like this:

{
    "name": "CRM Validation Extension",
    "description": "Extension that validate fields of a opportunity",
    "version": "0.1",
    "manifest_version": 3,
    "background": {
        "service_worker": "background.js"
    }
}

What can I do to solve this issue?

Thanks!

1 Answers1

0

I manage to solve the issue. Previously my manifest.json was like this:

{
    "name": "CRM Validation Extension",
    "description": "Extension that validate fields of a opportunity",
    "version": "0.1",
    "manifest_version": 3,
    "background": {
        "service_worker": "background.js"
    }
}

I changed the background object and replaced with the following:

"content_scripts":[
        {
            "matches": [
                "<all_urls>"
            ],
            "js": ["background.js"]
        }
    ]

This fixed the issue I was having.

  • 1
    It will prevent an access to chrome.contextMenus So, it doesn't resolve the issue. – Andrey Hohutkin Jun 30 '22 at 08:12
  • The background script/service worker and content script are quite separate things. This might be what you intended, but making this change will not help most people. – ChidG Jan 20 '23 at 01:54