[英]Is it possible to access the DOM of a website through a URL with javascript?
I understand that to access the DOM (document object Model) of a website through javascript you must use the Chrome console while on the website.. But what if I need to access the DOM of that same website but from an external document with extension.js or.html?我知道要通过 javascript 访问网站的 DOM(文档 object 模型),您必须在网站上使用 Chrome 控制台。但是如果我需要访问同一网站的 DOM,但需要从带有扩展名的外部文档访问。 js还是.html?
How can I access the DOM of a website without using the browser console?如何在不使用浏览器控制台的情况下访问网站的 DOM?
If the site does not have CORS restrictions, or if you're trying to connecting to a page from a page on the same origin, it's possible.如果该站点没有 CORS 限制,或者如果您尝试从同一来源的页面连接到页面,这是可能的。 Once you have the response text (which you can get with fetch
or XMLHttpRequest), you can turn it into a document with DOMParser
, and then you can navigate through it using DOM methods like querySelector
:获得响应文本(可以通过fetch
或 XMLHttpRequest 获得)后,您可以使用DOMParser
将其转换为文档,然后您可以使用 DOM 方法(如querySelector
)浏览它:
fetch('https://cors-anywhere.herokuapp.com/example.com/').then(res => res.text()).then((responseText) => { const doc = new DOMParser().parseFromString(responseText, 'text/html'); const h1 = doc.querySelector('h1'); console.log(h1.textContent); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.