我什至不知道我所要求的是否可行,我对网络开发还很陌生。
这是我想要实现的目标: 我需要在网页上执行JS脚本。该脚本返回一些与该页面相关的关键字。 我从远程服务器获取 JS 脚本并将其存储在字符串中。 我对该网页唯一了解的是它的 url,因此我使用 jQuery 获取该页面的内容。
这是我尝试过的(我知道这看起来很愚蠢,但它说明了我想要实现的目标):
// Let's say I want to execute that script on www.google.com's page
$.get("www.google.com", null, function(data) {
let myScript = localStorage.getItem('my_script')
// What I tried so far (it doesn't work, of course)
var temp = document.createElement('div')
temp.innerHTML = data
var resultsOfMyScript = temp.firstChild.eval(myScript) // not a function
})
你知道我该怎么做吗?
最佳答案
试试这个:
const script = document.createElement('script')
script.type = 'text/javascript'
script.charset = 'utf-8'
script.text = "console.log('this is my script')"
document.body.appendChild(script)
将 .text
替换为您提到的字符串。
关于javascript - 如何在存储在字符串中的 Html 代码上执行存储在字符串中的 JS 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43525057/