How To Run Javascript From A Bookmark

In this blog post, we will learn how to run JavaScript code from a bookmark, a simple yet powerful feature that can enhance your web browsing experience. This technique is known as bookmarklet and can be used to perform various tasks on web pages, such as modifying content, extracting data, and running custom scripts for web development and testing purposes. Let’s dive in!

What is a Bookmarklet?

A bookmarklet is a small piece of JavaScript code that can be stored as a bookmark in your web browser. When you click on it, the JavaScript code will be executed on the current web page, allowing you to manipulate the page content or execute specific tasks. Bookmarklets are compatible with most modern web browsers and don’t require any installation or additional software.

Creating a Bookmarklet

Creating a bookmarklet is simple. Follow these steps to create one:

  1. Open your favorite web browser and create a new bookmark (you can use the keyboard shortcut Ctrl + D or Cmd + D on macOS).
  2. Name your bookmark and, instead of adding a URL, paste your JavaScript code into the URL or Location field. Your code should start with the javascript: prefix, followed by an immediately invoked function expression (IIFE) containing your custom script. Here’s an example of a simple bookmarklet that displays an alert message:

    javascript:(function() { alert('Hello, World!'); })();

    Copy and paste the above code into your bookmark’s URL field.

  3. Save your bookmark. Now, whenever you click on your new bookmarklet, it will execute the JavaScript code on the active webpage.

Examples of Bookmarklets

Now that you know how to create a bookmarklet, let’s explore some examples of useful bookmarklets:

1. Change Background Color

This bookmarklet will change the background color of the webpage to a color of your choice:

javascript:(function() {
    var color = prompt('Enter a color:');
    document.body.style.backgroundColor = color;
})();

2. Display Page Title and URL

This bookmarklet will display the title and URL of the current webpage in an alert box:

javascript:(function() {
    alert('Title: ' + document.title + '\nURL: ' + location.href);
})();

3. Highlight All Links

This bookmarklet will highlight all the links on the webpage with a yellow background:

javascript:(function() {
    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        links[i].style.backgroundColor = 'yellow';
    }
})();

Conclusion

Bookmarklets are a versatile and powerful tool that allows you to run custom JavaScript code on any webpage with just a click. They can be used to perform various tasks, such as modifying the appearance of web pages, extracting data, and running custom scripts for development and testing purposes. Now that you know how to create and use bookmarklets, feel free to experiment and create your own to enhance your web browsing experience!