Search code examples
javascriptgoogle-chrome-extensionfirefox-addonfirefox-addon-webextensions

How can I get .getAttribute and .removeAttribute to match a[onclick*='ga']


I can't seem to get my Web Extension to block a[onclick*='ga'] as an attribute.

I've tried using

window.onload = function() {

let Removed = 0
const anchorElements = document.getElementsByTagName('A')

for (element of anchorElements) {
    if (!element.getAttribute('a[onclick*='ga']')) continue
            element.removeAttribute('a[onclick*='ga']')
            Removed += 1
            chrome.extension.sendMessage(Removed)
    }
}

and

window.onload = function() {

let Removed = 0
const anchorElements = document.getElementsByTagName('A')

for (element of anchorElements) {
    if (!element.getAttribute("onclick='ga'")) continue
            element.removeAttribute("onclick='ga'")
            Removed += 1
            chrome.extension.sendMessage(Removed)
    }
}

The result should be the extension removing any link with an onclick attribute of 'ga' and should then add 1 to removed which will update the extensions badge.


Solution

  • There are errors in your code. Here is an example for static content. If content is generated with JavaScript, it requires additional code.

    There is no need for window.onload

    document.querySelectorAll('a[onclick*="ga"]').forEach(item => item.removeAttribute('onclick'));
    

    If you want to keep a count

    const a = document.querySelectorAll('a[onclick*="ga"]');
    a.forEach(item => item.removeAttribute('onclick'));
    chrome.runtime.sendMessage(a.length);
    

    It is NOT a good idea to send an async message runtime.sendMessage inside the above loop.