步骤
使用eval执行脚本 脚本中有插值
代码如下:
var color = 'pink'
var stringCode =
`const div = document.createElement('div')
div.style.width = '100px'
div.style.height = '100px'
div.innerText = '脚本注入'
div.style.background = 'grey'
function fn (){
document.addEventListener('DOMContentLoaded', () => {
if (document.body.firstChild) {
document.body.insertBefore(div, document.body.firstChild)
} else {
document.body.appendChild(div)
}
})
}
setTimeout(function() { div.style.background = \`${color}\` } , 4000)
fn() `
eval(stringCode)
效果
也可以不使用插值 修改代码为
setTimeout(function() { div.style.background = color } , 2000)
效果是一样的