首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免document.write()

避免document.write()
EN

Stack Overflow用户
提问于 2020-12-08 11:08:10
回答 2查看 1.1K关注 0票数 1

我已经用PageSpeed Insight测试了我的网站,我有以下错误:避免document.write()。我的网站上有一个用于跟踪访问者的javascript代码:

代码语言: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。谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-08 11:36:42

建议: Element.append()

您可以使用document.createElement()创建一个元素。然后,可以将该元素附加到document.body

代码语言:javascript
复制
// 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的情况下插入脚本时容易受到脚本执行的影响。

该漏洞的示例(悬停在图像元素上以查看其效果):

代码语言:javascript
复制
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 + '">';

但是,如果您确信您构建的字符串是安全的,您可以添加这样的包含元素(用字符串替换下面的字符串占位符):

代码语言:javascript
复制
document.body.innerHTML += '<img alt="Some text">';
代码语言:javascript
复制
<p>I was here first!</p>

票数 2
EN

Stack Overflow用户

发布于 2022-04-11 13:36:16

我不推荐Element.innerHTML。编辑Element.innerHTML将一些给定的事件删除到元素中(例如VueJs应用程序)。最好使用document.body.append。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65197790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档