Browser debugging with bookmarklets

tl;dr

  • Bookmarklet are browser bookmarks that, instead of linking to a web page, inject custom javascript into the current page.
  • Here are a couple of bookmarklets I use regularly - to add them to your browser simply copy the minified code directly into the URL field for a new bookmark (remember to include the javascript: prefix).

Track current mouse coordinates

Use the below script to display the current mouse coordinates in the current tab title:

javascript: document.addEventListener("mousemove", (e) => {
  document.title = "X: " + e.pageX + " - Y: " + e.pageY;
});

It simply adds an event listener which updates the document title when the mouse moves.

Set the browser debugger to start after a countdown

The debugger command freezes all javascript execution on the current page. Often I want to freeze and inspect transient DOM states that only exist when the cursor is positioned over a component.

While in most cases a solution is simply to press F8 to pause execution, this sometimes doesn’t work if, for example, keydown event listeners are modifying parts of the DOM you are interested in. You could alternatively try putting a breakpoint on DOM mutations, but using a setTimeout to trigger the debugger is often more convenient.

Here is a script that prompts the user for the length of the countdown, and displays the countdown until the debugger is started in the console:

{
  let COUNTDOWN_MS = prompt("debugger will be called in X seconds: ") * 1000;
  const interval = setInterval(() => {
    if (COUNTDOWN_MS > 0) {
      console.log("debugger starting in " + COUNTDOWN_MS / 1000 + " s...");
      COUNTDOWN_MS -= 1000;
    } else {
      debugger;
      clearInterval(interval);
    }
  }, 1000);
}

For those interested in how it works, below is the same script without minification:

// use a block scope to avoid polluting the global namespace
{
  let COUNTDOWN_MS = prompt("debugger will be called in X seconds: ") * 1000;
  // setInterval returns an integer ID which allows it to be referred to later so it can be cleared
  const interval = setInterval(() => {
    if (COUNTDOWN_MS > 0) {
      console.log("debugger starting in " + COUNTDOWN_MS / 1000 + " s...");
      COUNTDOWN_MS -= 1000;
    } else {
      debugger;
      clearInterval(interval);
    }
  }, 1000);
}

Questions?

Do you have any useful scripts that could be made into bookmarklets? Do you have any questions or feedback? Feel free to leave a comment below, or to reach out to me directly.