javascript - 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.
解决方案
您的代码中有错误。这是静态内容的示例。如果内容是使用 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
在上述循环中发送异步消息不是一个好主意。
推荐阅读
- module - 我应该为我的 Guile 项目中的每个文件定义单独的模块吗?
- java - 如何使用 JPA 在运行时为实体使用不同的表?
- swift - RxSwift:如何通过视图调整大小来自动调整子层大小
- javascript - 如何根据 Firebase 中的值自动检查复选框?
- google-sheets - 如果工作表 2 上的“User_ID”与工作表 1 上的“User_ID”匹配,则从工作表 1 复制“名称”
- python - 如果从 PySimpleGUI 弹出单击 sg.Submit(),如何生成 file.txt?
- bigdata - Julia 中的大数组
- python - 如何将值返回到条目小部件
- reactjs - React App 与 Go 后端 api 通信
- node.js - API NodeJS如何查询和响应