簡體   English   中英

無法使用 javascript 訪問腳本標簽中存在的變量值

[英]Not able to access value of variable present inside a script tag using javascript

我正在嘗試訪問script標記中存在的變量的值。 但我無法檢索該值。 我嘗試了幾種方法,但沒有得到預期的結果。
我需要獲取值並解析並對其進行一些操作,但是我從早上就被阻止了,請問有人可以幫助我,這正在破壞我的時間。

 var scriptTag = document.getElementsById('test'); console.log(scriptTag.window["ytInitialData"]); //shows undefined console.log(scriptTag.getAttribite(window["ytInitialData"])); // shows null
 <script id="test"> window["ytInitialData"] = { "responseContext": { "serviceTrackingParams": [{ "service": "GFEEDBACK" }] } }; window["ytInitialPlayerResponse"] = { "responseContext": { "serviceTrackingParams": [{ "service": "GFEEDBACK" }] } }; if (window.ytcsi) { window.ytcsi.tick("pdr", null, ''); } </script>

window對象是全局的,可以從頁面上的任何腳本訪問,因此設置 window 屬性如下:

window.ytInitialData = {
    "responseContext": {
      "serviceTrackingParams": [{
        "service": "GFEEDBACK"
      }]
   }
}

“ytInitialData”是一個字符串文字,因此您可以使用點表示法而不是括號。

然后以相同的方式在腳本中的任何地方再次訪問它:

console.log(window.ytInitialData)

 window.ytInitialData = { "responseContext": { "serviceTrackingParams": [{ "service": "GFEEDBACK" }] } } console.log(window.ytInitialData)

暫無
暫無

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

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