JavaScript: Hostnames as self-executing fetches

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.

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 🤓

proxy-www

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.