DEV Community

Matt Kenefick
Matt Kenefick

Posted on

Bookmarklet for injecting scripts onto a page

javascript:(function() {
    let url;

    // Add frame to ensure we have access to `prompt`
    let iframe = document.createElement('iframe');
    document.body.appendChild(iframe);

    // Request data
    if (url = iframe.contentWindow.prompt('Enter script URL. Type "module" if you want loaded as a module.')) {
        var type = url.match(/\s?module\s?/) ? 'module' : 'text/javascript';
        url = url.replace(/\s?module\s?/, '');
        var x = document.createElement('script');
        if (url.toLowerCase().substr(0, 4) === 'http') {
            x.setAttribute('src', url);
        } else {
            x.innerHTML = url;
        }
        x.setAttribute('type', type);
        document.querySelector('head').appendChild(x);
    }

    // Remove
    document.body.removeChild(iframe);
})();
Enter fullscreen mode Exit fullscreen mode

If you create a bookmark with this code in it, it'll allow you to inject a script URL into the head of the page you're viewing.

It creates a temporary iframe just incase the top window overrides the prompt(...) command to prevent you from doing this.

There are some instances where the CSP of a page will prevent you from doing this, but it still works in many cases.

When it prompts you, you can give it responses like:

http://localhost:8080/script/my-script.js

// adds <script src="http://localhost:8080/script/my-script.js" type="text/javascript"></script>
Enter fullscreen mode Exit fullscreen mode

or

http://localhost:8080/script/my-script.js module

// adds <script src="http://localhost:8080/script/my-script.js" type="module"></script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)