javascript - 避免 document.write()
问题描述
我已经使用 PageSpeed Insights 测试了我的网站,但出现以下错误:避免使用 document.write()。我的网站上有一个用于跟踪访问者的 javascript 代码:
<script type="text/javascript" async>
document.write('<img src=\"https://traficwebsite/button.php?u=user&ref='+escape(document.referrer)+'&page='+escape(location.href.replace(/#.+$/,''))+'&rez='+screen.width+'x'+screen.height+'\" alt=\"DespreTrafic\" border=\"0\" width=\"1\" height=\"1\" />');
</script>
如何在此代码中替换 document.write。谢谢!
解决方案
推荐:Element.append()
您可以使用document.createElement()
. 然后可以将该元素附加到document.body
.
// Create an <img>-element
var img = document.createElement('img');
// Configure the attributes of your element
img.alt = 'An alternative text';
// Append it
document.body.append(img);
元素.innerHTML
您可以使用 .将字符串直接添加到 HTML 中Element.innerHTML
。但是,如链接中所述,当插入脚本而不使用<script>
-tag 时,这会使您的站点容易受到脚本执行的影响。
漏洞示例(将鼠标悬停在图像元素上以查看其效果):
var altText = 'some text" onmouseover="(() => {console.log(\'This lambda was executed!\')})()';
// This will add the following:
// <img alt="some text" onmouseover="(() => {console.log('This lambda was executed!')})()">
document.body.innerHTML += '<img alt="' + altText + '">';
但是如果你确定你构建的字符串是安全的,你可以像这样添加包含的元素(用你的字符串替换下面的字符串占位符):
document.body.innerHTML += '<img alt="Some text">';
<p>I was here first!</p>
推荐阅读
- python - 在同一页面中返回表单值
- javascript - 对象数组中嵌套对象的 Lodash 映射值
- python - /admin/auth/user/add/save() 的 TypeError 得到了一个意外的关键字参数“force_insert”
- flutter - TextFormField 上的 maxLength 属性仅适用于数字
- amazon-web-services - DynamoDB ThrottlingException 问题
- javascript - 转到页面然后运行该功能的锚标记
- ios - 如何正确实现 Amplify to Flutter
- kotlin - 传递给可变参数时,Kotlin 可以过滤掉空参数吗?
- javascript - React Native Navigation:有条件地渲染标签栏徽章不起作用?
- swift - 如何通过 SwiftUI Tap Gesture 使用键修饰符(选项/命令/控制)