如何让 .getAttribute 和 .removeAttribute 匹配 [onclick*='ga']

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

我似乎无法让我的 Web 扩展程序将 [onclick*='ga'] 作为属性来阻止。

我试过使用

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)
    }
}

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)
    }
}

结果应该是删除任何 link 且 onclick 属性为 'ga' 的扩展,然后应将 1 添加到删除,这将更新扩展徽章。

您的代码中有错误。 这是静态内容的示例。如果内容是用 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 不是一个好主意。