DEV Community

Yawar Amin
Yawar Amin

Posted on

Bookmarklets, and why you should use them

MOST of us have been using web browsers for a long time, yet relatively few of us know this somewhat obscure feature: browsers understand URLs that begin with javascript: instead of http: or https: protocols, and can actually execute the JavaScript code in the URL when you request it. Sounds like a security nightmare? Potentially, yes. You should be careful about what URLs you click on.

However! Harnessed in the right way, these javascript: URLs can be incredibly useful–enter bookmarklets.

What are they

Bookmarklets are just regular browser bookmarks except that they have a javascript: URL:

Name: (whatever name you want)

URL: javascript:/* code */

For example, javascript:alert('hi!').

OK, so an alert pop-up is not that useful. But bookmarklets can do anything that JavaScript running on the page can. Even better, they allow you to replace some browser extensions that have similar functionality. For power users, instead of the memory overhead of a loaded browser extension, you replace it with a zero-cost bookmarklet.

Let me show you two very simple and useful bookmarklets and explain how they work.

Allow paste

URL: javascript:document.addEventListener('paste', e => e.stopImmediatePropagation(), true)

When you click on this, it will 'trap' all paste events from further handling by JavaScript code, but allow the actual paste to go ahead. Why would you need this? Well, some annoying websites like to disable paste functionality by setting their own paste event handlers on certain text inputs. They think that eg if you can't paste a password, you will be forced to type it in, which for some reason will make it more secure.

Of course, that's nonsense. But that's the kind of reasoning these sites have (I guess). So we circumvent these geniuses by taking control of our own paste events.

This allows you to get rid of: Don't F*** With Paste

Scroll top/bottom

URL: javascript:window.scrollTo(0, window.scrollY == 0 ? document.body.scrollHeight : 0)

When clicked, this will:

  • If at the top of the page, scroll to the bottom
  • Else, scroll to the top

Simple, yet effective.

This allows you to get rid of: Scroll To Top

And more

These are just two simple use cases. As you can imagine, anything you can do with JavaScript on a web page, you can do with bookmarklets. Even making HTTP requests with the Fetch API! You're limited only by your imagination.

I have a collection of bookmarklets if you are interested in more. Have fun 🙂

Top comments (0)