You can use XMLHttpRequest
or Fetch
to perform a request to get the source code for the page. After that, just use document.createElement
or DOMParser
to be able to "convert" the returned source code (like string ) to HTML .
Example with XMLHttpRequest
and document.createElement
:
XMLHttpRequest
is an API that provides functionality to the client to transfer data between a client and a server. It provides an easy way to retrieve data from a URL without having to do a full page update. Since document.createElement
will create an HTML element, this way we can use functions like 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/pt-BR/")
xhr.send()
}
JavaScript:
<button onclick="copy()">Click!</button>
<div id="result"></div>
Example with Fetch
and DOMParser
:
The Fetch API provides an interface for fetching resources (for example, across the network). It will look familiar to anyone who has used XMLHttpRequest , however the new API offers a more powerful and flexible feature set. The
DOMParser
function will convert our string to HTML , so we can use functions like
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 Access-Control-Allow-Origin
header.
For more details I recommend the HTTP Access Control (CORS) .