簡體   English   中英

如何在存儲在字符串中的Html代碼上執行存儲在字符串中的JS腳本

[英]How to execute a JS Script stored in a string on Html code stored in a string

我甚至不知道我問的是否可能,我對網絡開發還不熟悉。

這是我想要實現的:我需要在網頁上執行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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM