Skip to content

Instantly share code, notes, and snippets.

@toraritte
Last active February 10, 2023 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toraritte/e9d7a01dba1fd6a55c65b36274cd35cb to your computer and use it in GitHub Desktop.
Save toraritte/e9d7a01dba1fd6a55c65b36274cd35cb to your computer and use it in GitHub Desktop.

What is a bookmarklet?

a small software application stored as a bookmark in a web browser, which typically allows a user to interact with the currently loaded web page in some way.

That is, when the URL field of a bookmark contains JavaScript. This one is for printing internal docs to PDF by simply clicking on a bookmark:

javascript: (() => { let auth_num = document.body.outerHTML.match(/NMED\d{9}/g); let datetime = new Date().toJSON().replace(/[^a-zA-Z0-9]/g, '_'); document.title = `${datetime}_${auth_num}`; window.print(); window.close(); })();

Breaking it down

1. The bookmarklet JavaScript template

javascript: (() => { /* add arbitrary code here */ })();

2. The "inner" JavaScript

// These parts are irrelevant as they
// are specific to internal HTML documents.
let auth_num = document.body.outerHTML.match(/NMED\d{9}/g);
let datetime = new Date().toJSON().replace(/[^a-zA-Z0-9]/g, '_');

// Change  title  of the HTML  document as this 
// will be the default name of the printed PDF.
document.title = `${datetime}_${auth_num}`;

// Open print dialog (same and CTRL+P).
window.print();

// (Optional) Close the browser tab.
// Only works if that has been opened programmatically!
// (Such as using Vimium plugin in Chrome.)
window.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment