[英]Not able to access value of variable present inside a script tag using javascript
I am trying to access the value of a variable present inside a script
tag.我正在尝试访问script
标记中存在的变量的值。 But I am not able to retrieve the value.但我无法检索该值。 I tried in few ways but I don't get the expected result.我尝试了几种方法,但没有得到预期的结果。
I need to get the values and parse and do some operations over it but I am blocked from morning can u please some one help me it's ruining my time.我需要获取值并解析并对其进行一些操作,但是我从早上就被阻止了,请问有人可以帮助我,这正在破坏我的时间。
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>
The window
object is global and can be accessed from any script on your page, so set the window property like this: window
对象是全局的,可以从页面上的任何脚本访问,因此设置 window 属性如下:
window.ytInitialData = {
"responseContext": {
"serviceTrackingParams": [{
"service": "GFEEDBACK"
}]
}
}
"ytInitialData" is a string literal so you can use dot notation instead of brackets. “ytInitialData”是一个字符串文字,因此您可以使用点表示法而不是括号。
Then access it again anywhere later in your script the same way:然后以相同的方式在脚本中的任何地方再次访问它:
console.log(window.ytInitialData)
window.ytInitialData = { "responseContext": { "serviceTrackingParams": [{ "service": "GFEEDBACK" }] } } console.log(window.ytInitialData)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.