如何从通过xhr请求获取的页面的HTML源中的scripts标签访问变量值。
已获取页面的HTML ...
<html>
<body>
<div id="somecontent"></div>
<script>
var foo="30";
</script>
<script>
var bar="60";
</script>
</body>
</html>
并通过xhr请求获取...
var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
// try to access var
var result =html.foo+html.bar;
console.log(result);
}
}
xhr.send();
任何想法将不胜感激!
答案 0 :(得分:1)
您可以尝试类似的操作:
var xhr = new XMLHttpRequest();
xhr.open("GET","http://www.example.com/testpage.html");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var html = xhr.responseText;
var parser = new DOMParser();
var dom = parser.parseFromString(html, 'text/html');
var scripts = dom.querySelectorAll('script');
for (let script of scripts) {
eval(script.innerText);
}
console.log('foo', foo);
console.log('bar', bar);
}
}
xhr.send();