我已经用PageSpeed Insight测试了我的网站,我有以下错误:避免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。谢谢!
发布于 2020-12-08 11:36:42
建议: 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);
Element.innerHTML
可以使用Element.innerHTML将字符串直接添加到HTML中。但是,正如链接中所提到的,这使您的站点在不使用<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>
发布于 2022-04-11 13:36:16
我不推荐Element.innerHTML。编辑Element.innerHTML将一些给定的事件删除到元素中(例如VueJs应用程序)。最好使用document.body.append。
https://stackoverflow.com/questions/65197790
复制相似问题