You can use the XMLHttpRequest
or Fetch
to make a request to get source code from the page. After that, just use document.createElement
or DOMParser
to be able to "convert" the returned source code (such as string) for HTML.
Example with XMLHttpRequest
and document.createElement
:
XMLHttpRequest
is an API that provides client functionality to transfer data between a client and a server. It provides an easy way to recover data from a URL without having to do a full page update. Already the document.createElement
will create an element HTML, in this way we can use functions such as querySelector
and filter certain elements.
Javascript:
const result = document.querySelector("#result")
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", event => {
/**
* Cria um elemento temporário
* Adiciona o código fonte retornado
*/
const html = document.createElement("html")
html.innerHTML = event.target.response
/* Captura todos os links com o atributo rel="bookmark" */
const anchors = html.querySelector("a[rel=\"bookmark\"]");
/* Adiciona os links capturados na div#result */
anchors.forEach(anchor => {
result.innerHTML += anchor
})
})
function copy() {
/* Realiza a requisição */
xhr.open("GET", "https://developer.mozilla.org/en-US/")
xhr.send()
}
Javascript:
<button onclick="copy()">Click!</button>
<div id="result"></div>
Example with Fetch
and DOMParser
:
To Fetch API provides an interface to search for resources (for example, across the network). It will look familiar to anyone who has used Xmlhttprequest, but the new API offers a more powerful and flexible feature set. The function DOMParser
will convert our string for HTML, in this way we can use functions such as querySelectorAll
to filter useful elements.
Javascript:
const result = document.querySelector("#result")
function copy() {
fetch("https://developer.mozilla.org/")
.then( response => response.text())
.then( response => {
/**
* Cria um elemento temporário
* Adiciona o código fonte retornado
*/
const parser = new DOMParser()
const html = parser.parseFromString(response, "text/html")
/* Captura todos os links com o atributo rel="bookmark" */
const anchors = html.querySelector("a[rel=\"bookmark\"]")
/* Adiciona os links capturados na div#result */
anchors.forEach(anchor => {
result.insertAdjacentHTML('beforeend', anchor)
})
})
}
HTML:
<button onclick="copy()">Click!</button>
<div id="result"></div>
Restriction:
For security reasons, browsers are blocking requests on pages that do not have the header Access-Control-Allow-Origin
.
For more details recommend the page HTTP Access Control (CORS).