Created
April 17, 2019 08:31
-
-
Save docteurklein/588b8311fb751314a7fbce1ad4c0cfe1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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