This content originally appeared on Bram.us and was authored by Bramus!
In a conversation between Mathias Bynens and Ingvar Stepanyan, an idea popped up: what if a hostname — such as www.bram.us
— would be valid JavaScript? Using a JavaScript Proxy
, that’s perfect possible.
My favourite is hostnames being valid (and working!) JavaScript.
— Ingvar Stepanyan (@RReverser) June 12, 2019
Building further upon that is proxy-www
, which creates self-executing fetches from them.
const www = new Proxy(new URL('https://www'), {
get: function get(target, prop) {
let o = Reflect.get(target, prop);
if (typeof o === 'function') {
return o.bind(target)
}
if (typeof prop !== 'string') {
return o;
}
if (prop === 'then') {
return Promise.prototype.then.bind(fetch(target));
}
target = new URL(target);
target.hostname += `.${prop}`;
return new Proxy(target, { get });
}
});
Usage:
www.baidu.com.then(response => {
console.log(response.status);
})
My inner geek rejoices ?
This content originally appeared on Bram.us and was authored by Bramus!
Bramus! | Sciencx (2021-07-20T22:08:08+00:00) JavaScript: Hostnames as self-executing fetches. Retrieved from https://www.scien.cx/2021/07/20/javascript-hostnames-as-self-executing-fetches/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.