javascript - 阻止执行特定的内联脚本标签
问题描述
我正在尝试为Tampermonkey编写一个脚本,以防止执行特定的内联脚本标记。页面的主体看起来像这样
<body>
<!-- the following script tag should be executed-->
<script type="text/javascript">
alert("I'm executed as normal")
</script>
<!-- the following script tag should NOT be executed-->
<script type="text/javascript">
alert("I should not be executed")
</script>
<!-- the following script tag should be executed-->
<script type="text/javascript">
alert("I'm executed as normal, too")
</script>
</body>
我尝试使用我的 Tampermonkey 脚本删除标签script
,但如果我运行它 document-start
或标签尚不存在。如果我运行它或者我想删除的标签在我的 Tampermonkey 脚本执行之前运行。document-body
script
document-end
document-idle
script
如何防止script
标签的执行?
注意:script
我想阻止执行的实际标签包含window.location = 'redirect-url'
. 因此,在这种情况下防止重新加载也足够了。
版本:
- 铬 65.0.3325.181
- 篡改猴子 4.5
解决方案
删除脚本标记document-start
(如wOxxOm建议的那样):
(function() {
'use strict';
window.stop();
const xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href);
xhr.onload = () => {
var html = xhr.responseText
.replace(/<script\b[\s\S]*?<\/script>/g, s => {
// check if script tag should be replaced/deleted
if (s.includes('window.location')) {
return '';
} else {
return s;
}
});
document.open();
document.write(html);
document.close();
};
xhr.send();
})();
推荐阅读
- sanity - Sanity io 显示作者的博客文章
- typescript - 使用泛型接口的泛型函数
- python - 将 Twitter 数据的大型 JSONL (32gb) 转换为 CSV 或数据帧(R 或 Python)
- calendar - Nextcloud:如何更改数据库中日历事件的颜色?
- r - 如何重塑数据框,使每个 id 只有 1 个观察值?
- amazon-web-services - 使用 AWS CLI 为 AWS Cognito 池生成访问令牌
- assembly - 使用命名堆栈参数编写一个过程
- salesforce - 尝试将重定向页面上的输出链接添加到来自另一个 VF 页面的新创建的机会
- python-3.x - 在分割模型库中将最终预测的图像尺寸改回其原始尺寸
- c - http 请求标头 - 从 URI 中删除的一些特殊字符