Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 1x 1x | /**
* A simple class that implements fetches.
*/
export class pjax {
/**
* Makes a fetch to url and filter the result with a query selector.
*
*
* ```
* import { pjax } from 'degu/lib/dom/pjax';
*
* pjax.fetch('/my-page', '.hello-div').then((result)=> {
*
* console.log(result['queryHtml']); // The fetch result. HTML as string.
* console.log(result['fullPageHtml']); // The full page html of the fetched page.
* console.log(result['head']); // The head content of the fetched page.
*
*
* // Inject the result into a page.
* document.querySelector('.mydiv').innerHTML = result['queryHtml'];
*
* // Update the head if you want.
* document.querySelector('head').innerHTML = result['head'];
*
* })
* ```
*
* @param url
* @param querySelector
*/
static fetch(
// The URL to fetch.
url: string,
// After fetching, filter the result by running a query selector.
querySelector: string
): Promise<Object> {
return new Promise((resolve, error) => {
fetch(url)
.then((response) => {
return response.text();
})
.then((html: string) => {
resolve({
queryHtml: pjax.queryHtmlString(html, querySelector),
fullPageHtml: html,
head: pjax.getHead(html),
});
})
.catch((err) => {
error(err);
});
});
}
/**
* Given an html string, queries the content.
*/
static queryHtmlString(
html: string,
targetElementQuerySelection: string
): string {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.querySelector(targetElementQuerySelection)!.innerHTML;
}
/**
* Given an html string, returns the head.
*/
static getHead(html: string) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.head.innerHTML;
}
}
|