Skip to content

Instantly share code, notes, and snippets.

@docteurklein
Created April 17, 2019 08:31
Show Gist options
  • Save docteurklein/588b8311fb751314a7fbce1ad4c0cfe1 to your computer and use it in GitHub Desktop.
Save docteurklein/588b8311fb751314a7fbce1ad4c0cfe1 to your computer and use it in GitHub Desktop.
<script type="module">
export default class RemoteContent extends HTMLElement {
constructor() {
super();
this.parser = new DOMParser();
this.shadow = this.attachShadow({mode: 'open'});
this.append = this.shadow.appendChild.bind(this.shadow);
this.shadow.innerHTML = 'loading…';
}
static get observedAttributes() {
return ['url', 'selector'];
}
connectedCallback() {
this.fetch(this.getAttribute('url'), this.getAttribute('selector') || 'body');
}
async fetch(url, selector) {
let response = await fetch(url);
let doc = this.parser.parseFromString(await response.text(), 'text/html');
this.shadow.innerHTML = '';
doc.querySelectorAll('link[rel=stylesheet]').forEach(this.append);
doc.querySelectorAll(selector).forEach(this.append);
}
}
customElements.define('remote-content', RemoteContent);
</script>
<remote-content url="https://ask-franklin.cloud.akeneo.com"></remote-content>
<remote-content url="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" selector="h1,h2,h3"></remote-content>
<remote-content url="https://cors-anywhere.herokuapp.com/https://news.ycombinator.com/" selector=".athing"></remote-content>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment