首页 > 解决方案 > 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.

标签: javascriptgoogle-chrome-extensionfirefox-addonfirefox-addon-webextensions

解决方案


您的代码中有错误。这是静态内容的示例。如果内容是使用 JavaScript 生成的,则需要额外的代码。

没有必要window.onload

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

如果你想保持计数

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

runtime.sendMessage在上述循环中发送异步消息不是一个好主意。


推荐阅读