目录
JS原生开发-DOM树-用户交互
随便下载两张照片放到之前的 js 目录下
创建 dom.html, 内容如下:演示获取图片 src 和标签文本
<h1 id="myHeader" onclick="update1()">这是H1</h1>
<img src="iphone.jpg" width="300" height="300"><br>
<button onclick="update()">刷新</button>
<script>
function update(){
const img=document.querySelector('img');
console.log(img.src);
}
function update1(){
const h1=document.querySelector('h1');
console.log(h1.innerText);
}
</script>
这里开始演示点击刷新修改图片和点击文本修改标签文本
<!--<h1 id="myHeader" onclick="update1()">这是标题</h1>-->
<!--<img src="iphone.jpg" width="300" height="300"><br>-->
<!--<button onclick="update()">刷新</button>-->
<!--<script>-->
<!-- function update(){-->
<!-- const s=document.querySelector('img')-->
<!-- s.src="javascript:alert(‘XSS’);"-->
<!-- //如果这里huawei.png为一个变量由用户传递决定,那么就会造成DOM XSS-->
<!-- }-->
<!-- function update1(){-->
<!-- const s=document.querySelector('h1')-->
<!-- //s.innerText="这是小迪<br>"-->
<!-- s.innerHTML='<img src=# onerror="alert(1)">'-->
<!-- console.log(str)-->
<!-- }-->
<!--</script>-->
<!--<h1 id="myHeader" onclick="update1()">这是H1</h1>-->
<!--<img src="iphone.jpg" width="300" height="300"><br>-->
<!--<button onclick="update1()">刷新</button>-->
<!--<script>-->
<!-- function update(){-->
<!-- const img=document.querySelector('img');-->
<!-- console.log(img.src);-->
<!-- }-->
<!-- function update1(){-->
<!-- const h1=document.querySelector('h1');-->
<!-- console.log(h1.innerText);-->
<!-- }-->
<!--</script>-->
<h1 id="myHeader" onclick="update1()">这里是SuYou</h1>
<img src="iphone.jpg" width="300" height="300"><br>
<button onclick="update()">刷新</button>
<script>
function update(){
const img=document.querySelector('img');
img.src = 'huawei.png';
console.log(img.src);
}
function update1(){
const h1=document.querySelector('h1');
const str = h1.innerText;
console.log(str);
// 迪总是置换了文本,我让它点一下左移一下,小把戏,见笑见笑
const first = str[0];
var remain = str.substring(1,str.length);
var new_str = remain + first;
h1.innerText = new_str; // innerText不解析后续代码,只是当文本
// h1.innerHTML = '<h3>' + new_str + '</h3>'; // innerHTML不解析后续代码,只是当文本
}
</script>
此时点击 h1 刷新标题内容,点击刷新按钮,刷新照片
安全问题:本身的前端代码通过DOM技术实现代码的更新修改,但是更新修改如果修改的数据可以由用户来指定,就会造成DOM-XSS攻击!
如 update 中的 img.src, 如果这里的 huawei.png 为一个变量,可以由用户传递决定,那么就可能会造成 DOM XSS, 如下
<h1 id="myHeader" onclick="update1()">这是标题</h1>
<img src="iphone.jpg" width="300" height="300"><br>
<button onclick="update()">刷新</button>
<script>
function update(){
const s=document.querySelector('img')
s.src="javascript:alert(‘XSS’);"
//如果这里huawei.png为一个变量由用户传递决定,那么就会造成DOM XSS
}
function update1(){
const s=document.querySelector('h1')
//s.innerText="这是小迪<br>"
s.innerHTML='<img src=# onerror="alert(1)">'
console.log(str)
}
</script>
点击刷新:可见浏览器进行了过滤拦截
点击标题,绕过
update1 函数通过 innerHTML 插入带有 onerror 事件的 img 元素,这可能导致 XSS(跨站脚本攻击)漏洞。在实际应用中,需要谨慎处理用户提供的内容,以防止安全漏洞。