[英]How to execute a JS Script stored in a string on Html code stored in a string
I don't even know if what I'm asking is possible or not, I'm fairly new to web development. 我甚至不知道我问的是否可能,我对网络开发还不熟悉。
Here is what I'd like to achieve: I need to execute a JS script on a web page. 这是我想要实现的:我需要在网页上执行JS脚本。 The script returns some keywords related to that page.
该脚本返回与该页面相关的一些关键字。 I get the JS script from a remote server and I store it in a string.
我从远程服务器获取JS脚本,并将其存储在字符串中。 The only thing I know about the web page is its url, so I get the content of the page with jQuery.
我对网页唯一了解的是它的url,所以我用jQuery获取了页面的内容。
Here is what I tried (I know it looks stupid, but it illustrates what I'm trying to achieve): 这是我尝试过的(我知道它看起来很愚蠢,但它说明了我想要实现的目标):
// 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
})
Do you have any idea on how I could do that? 你对我怎么做到了吗?
Try this: 尝试这个:
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)
Substitute .text
for the string you mentioned. 替换你提到的字符串的
.text
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.