Hey, everyone!
Today, I want to share something with you called a Bookmarklet. What is that? Read on to find out!!
What is a Bookmarklet?
A bookmarklet is a small piece of JavaScript code that can be saved as a bookmark in a web browser. When the bookmarklet is clicked, it executes the JavaScript code on the current webpage, performing a specific action or enhancing the functionality of the page. They're awesome! So let's find out how to make one!
How to Make a Bookmarklet
To add a bookmarklet to your browser, make sure you can see your bookmarks bar (sometimes called a "favorites" bar). To add a bookmarklet, follow these steps:
- Right-click on your bookmark bar and select "Add Site" or a similar option.
- Give your bookmarklet a name.
- Replace the address with a JavaScript code like this one:
javascript:(function() {
/*Your code goes here*/
})();
The code above is a JavaScript self-executing function. When you click on the bookmarklet, it will run. The great thing about bookmarklets is that they can interact with the page you're on. There are some important limitations of bookmarklets, though! Let's look at those below.
Limitations to Keep in Mind
Here are some tips based on my experience to help you create effective (and functional) bookmarklets:
-
Avoid Single Line Comments: Single line comments (
//Comment
) can be problematic and difficult to troubleshoot in bookmarklets. Since bookmarklets are only one line long, using the//
method effectively comments out everything after it. Instead, use/*Comment*/
to comment out multiple lines. -
Be Aware of Cross-Origin Requests: Depending on your browser version and settings, bookmarklets making requests to APIs may have the origin
null
. This can sometimes cause issues when making requests to APIs in a bookmarklet. -
Minimize External Dependencies: Unfortunately, it is not practical (and sometimes not possible) to include external dependencies like
<script src="https://url.com/">
in a bookmarklet. Keep this in mind when writing your code. - Consider Code Length Limitations: Some browsers may have limitations on the number of characters allowed in a bookmark. While I haven't personally encountered this, it's a good practice to minify or compress your code if you suspect it may exceed the character limit.
With these considerations in mind, you're ready to create your own bookmarklet! So let's get started with the examples below.
Bookmarklet 1: QR Code Generator
This bookmarklet makes use of a free API, https://api.qrserver.com
. It is a relatively simple code that generates a QR code for any page by going to the API link with the current page URL inputted into the ?data=
(data) parameter. Here is the code:
javascript:(function() { var url = encodeURIComponent(window.location.href); var qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?data=" + url; window.open(qrCodeUrl, "_blank");})();
As you can see, not too long. Most bookmarklets are relatively simple.
Bookmarklet 2: Translate Page
This bookmarklet uses Google Translate to translate any page that you are on. When clicked, it prompts for the language (two-letter code, e.g., βFrenchβ β βfrβ), and opens the translated page. Here is the code:
javascript:(function() { var lang = prompt("Enter language code to translate to:", "en"); var translationUrl = "https://translate.google.com/translate?sl=auto&tl=" + lang + "&u=" + encodeURIComponent(window.location.href); window.open(translationUrl, "_blank");})();
Bookmarklet 3: Dark Mode
This bookmarklet will turn a page into dark mode (or try to). It may break some pages.
javascript:(function() { var style = document.createElement('style'); style.innerHTML = ` * { color: white !important; background-color: #111000 !important; } %60; document.head.appendChild(style);})();
Bookmarklet 4: Password Generator
This handy bookmark generates a random password. You are prompted for a length, and a password is generated. This bookmark especially makes use of the very convenient placeholder for browser APIs like prompts.
javascript:(function() { function generatePassword(length) { var charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-+={}|:"?#$*'; var password = ''; for (var i = 0; i < length; i++) { var randomIndex = Math.floor(Math.random() * charset.length); password += charset.charAt(randomIndex); } return password; } var passwordLength = prompt("Enter password length:", "8"); var generatedPassword = generatePassword(passwordLength); prompt("Generated Password:", generatedPassword);})();
This one is a bit long, but it shouldn't cause any trouble.
Bookmarklet 5: Email Copier
If you are like me and are paranoid about mistyping your email, this bookmarklet is right for you. Substitute you@example.com
with your real email.
javascript:(function() { const email = "you@example.com"; const dummyElement = document.createElement("textarea"); document.body.appendChild(dummyElement); dummyElement.value = email; dummyElement.select(); document.execCommand("copy"); document.body.removeChild(dummyElement);})();
Personally, though this is one of the simpler ones, it is one of the most useful for me.
Bookmarklet 6: Page Word Count
This bookmarklet was one of my first. Kind of boring, but I figured I might as well put it here. When you click the bookmark, it scans the page and tells you how many words are on it. Code:
javascript:(function() { var text = document.body.innerText || document.body.textContent; var words = text.trim().split(/\s+/).length; alert("Word Count: " + words);})();
Bookmarklet 7: SEO Tips Bookmark
OK, not fully functional, but I put 20 SEO tips in it to get you started:
javascript:(function() { var pageUrl = window.location.href; var tips = processDiagnosticData(); if (tips) { alert('Page Diagnosis Tips:\n\n' + tips); } function processDiagnosticData() { var tips = ''; var titleTag = document.querySelector('title'); if (!titleTag) { tips += 'Title Tag is missing\n'; } var metaDescriptionTag = document.querySelector('meta[name="description"]'); if (!metaDescriptionTag) { tips += 'Meta Description is missing\n'; } var headingTags = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); if (headingTags.length === 0) { tips += 'Heading Tags are missing\n'; } var imgTags = document.querySelectorAll('img'); if (imgTags.length === 0) { tips += 'Image Tags are missing\n'; } var anchorTags = document.querySelectorAll('a'); if (anchorTags.length === 0) { tips += 'Anchor Tags are missing\n'; } var scriptTags = document.querySelectorAll('script'); if (scriptTags.length === 0) { tips += 'Script Tags are missing\n'; } var linkTags = document.querySelectorAll('link'); if (linkTags.length === 0) { tips += 'Link Tags are missing\n'; } var metaViewportTag = document.querySelector('meta[name="viewport"]'); if (!metaViewportTag) { tips += 'Viewport Meta Tag is missing\n'; } var canonicalTag = document.querySelector('link[rel="canonical"]'); if (!canonicalTag) { tips += 'Canonical Tag is missing\n'; } var robotsTag = document.querySelector('meta[name="robots"]'); if (!robotsTag) { tips += 'Robots Meta Tag is missing\n'; } var ogTags = document.querySelectorAll('meta[property^="og:"]'); if (ogTags.length === 0) { tips += 'Open Graph Tags are missing\n'; } var twitterTags = document.querySelectorAll('meta[name^="twitter:"]'); if (twitterTags.length === 0) { tips += 'Twitter Card Tags are missing\n'; } var altAttributes = document.querySelectorAll('img:not([alt])'); if (altAttributes.length > 0) { tips += 'Alt Attributes are missing for some Images\n'; } var formTags = document.querySelectorAll('form'); if (formTags.length === 0) { tips += 'Form Tags are missing\n'; } var inputTags = document.querySelectorAll('input'); if (inputTags.length === 0) { tips += 'Input Tags are missing\n'; } var textareaTags = document.querySelectorAll('textarea'); if (textareaTags.length === 0) { tips += 'Textarea Tags are missing\n'; } var buttonTags = document.querySelectorAll('button'); if (buttonTags.length === 0) { tips += 'Button Tags are missing\n'; } var tableTags = document.querySelectorAll('table'); if (tableTags.length === 0) { tips += 'Table Tags are missing\n'; } var metaCharsetTag = document.querySelector('meta[charset]'); if (!metaCharsetTag) { tips += 'Charset Meta Tag is missing\n'; } return tips; }})();
Very much on the long side, but it will do okay.
Bookmarklet 8: Element Highlighter
Basically, it changes the colors of all page elements, so you can see them:
I really love this one as it can show me with just one click the layout of the page. So useful.
Here is the code:
javascript:(function(){ function getRandomColor() { var letters = "0123456789ABCDEF"; var color = "#"; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } function getContrastingColor(color) { var hex = color.slice(1); var r = parseInt(hex.substr(0, 2), 16); var g = parseInt(hex.substr(2, 2), 16); var b = parseInt(hex.substr(4, 2), 16); var yiq = (r * 299 + g * 587 + b * 114) / 1000; return yiq >= 128 ? "#000000" : "#FFFFFF"; } function applyRandomStyle(element) { var randomColor = getRandomColor(); element.style.backgroundColor = randomColor; element.style.color = getContrastingColor(randomColor); } var elements = document.getElementsByTagName("*"); for (var i = 0; i < elements.length; i++) { applyRandomStyle(elements[i]); }})();
This one is certainly interesting for developers; it has helped me find problems with pages before.
Bookmarklet 9: JSON Formatter
This bookmarklet formats JSON API responses:
Before:
After:
Incredibly useful if you do lots of API stuff like me.
Code:
javascript:(function() { function syntaxHighlight(json) { json = JSON.stringify(json, undefined, 4); json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, function (match) { var cls = %27color: black;%27; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = %27color: green;%27; } else { cls = %27color: darkorange;%27; } } else if (/true|false/.test(match)) { cls = %27color: red;%27; } else if (/null|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/.test(match)) { cls = %27color: purple;%27; } return %27<span style="%27 + cls + %27">%27 + match + %27</span>%27; }); } var contentType = document.contentType; if (contentType === "application/json") { var json = JSON.parse(document.body.innerText); var highlighted = syntaxHighlight(json); document.body.innerHTML = %27<pre>%27 + highlighted + %27</pre>%27; document.body.style.fontFamily = "Arial, sans-serif"; document.body.style.fontSize = "15px"; } else { alert("This page does not contain JSON."); }}());
Might actually be my favorite? Too hard to choose.
Bookmarklet 10: Color Picker
Opens a color picker on any page so you can use it for your web dev stuff. Pretty simple.
javascript:(function(){ var container = document.createElement('div'); container.style.position = 'fixed'; container.style.top = '10px'; container.style.right = '10px'; container.style.zIndex = '9999'; container.style.backgroundColor = 'white'; container.style.borderRadius = '10px'; container.style.padding = '10px'; container.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.3)'; container.style.display = 'flex'; container.style.alignItems = 'center'; var colorInput = document.createElement('input'); colorInput.type = 'color'; colorInput.style.width = '30px'; colorInput.style.height = '30px'; colorInput.style.marginRight = '10px'; var copyButton = document.createElement('button'); copyButton.textContent = 'Copy'; copyButton.style.padding = '5px 10px'; copyButton.style.marginRight = '10px'; copyButton.style.backgroundColor = '#4CAF50'; copyButton.style.color = 'white'; copyButton.style.border = 'none'; copyButton.style.borderRadius = '5px'; copyButton.style.cursor = 'pointer'; var closeButton = document.createElement('button'); closeButton.textContent = 'Close'; closeButton.style.padding = '5px 10px'; closeButton.style.backgroundColor = '#f44336'; closeButton.style.color = 'white'; closeButton.style.border = 'none'; closeButton.style.borderRadius = '5px'; closeButton.style.cursor = 'pointer'; copyButton.addEventListener('click', function() { var color = colorInput.value; var tempInput = document.createElement('input'); tempInput.value = color; document.body.appendChild(tempInput); tempInput.select(); document.execCommand('copy'); document.body.removeChild(tempInput); alert('Color copied to clipboard: ' + color); }); closeButton.addEventListener('click', function() { container.remove(); }); container.appendChild(colorInput); container.appendChild(copyButton); container.appendChild(closeButton); document.body.appendChild(container);})();
Bookmarklet 11: Desktop Eyedropper
Attribution: This was submitted by @aarvinr on dev.to. Be sure to check him out!
This super handy bookmarklet lets you pick a color not just from the page, but from the whole desktop!
Check out it's GitHub repository here:
https://github.com/twogrey/CoPiBoo---Color-Picker-Bookmarklet
The demo is here:
https://twogrey.github.io/CoPiBoo---Color-Picker-Bookmarklet/
This doesn't work in some Linux distributions, but it works fine on Windows.
Bookmarklet 12: Restart Browser
Not a real bookmarklet, but cool, so I had to add it:
Only works in Chrome based browsers. Just make a bookmark with chrome://restart/
as the URL. It will restart your browser when you click it.
Bookmarklet 13: Page Performance Test
This bookmarklet performs a page performance test on the current page using Google PageSpeed Insights.
Code:
javascript:window.location='https://developers.google.com/speed/pagespeed/insights/?url=%27+encodeURI(window.location);
Pretty simple, really.
Bookmarklet 14: Ad Blocker
Removes ads from the current page.
Code:
javascript:(function(){ /* Ad-B-Gone: Bookmarklet that removes obnoxious ads from pages */ var selectors = [ /* By ID: */ '#sidebar-wrap', '#advert', '#xrail', '#middle-article-advert-container', '#sponsored-recommendations', '#around-the-web', '#sponsored-recommendations', '#taboola-content', '#taboola-below-taboola-native-thumbnails', '#inarticle_wrapper_div', '#rc-row-container', '#ads', '#at-share-dock', '#at4-share', '#at4-follow', '#right-ads-rail', 'div#ad-interstitial', 'div#advert-article', 'div#ac-lre-player-ph', /* By Class: */ '.ad', '.avert', '.avert__wrapper', '.middle-banner-ad', '.advertisement', '.GoogleActiveViewClass', '.advert', '.cns-ads-stage', '.teads-inread', '.ad-banner', '.ad-anchored', '.js_shelf_ads', '.ad-slot', '.antenna', '.xrail-content', '.advertisement__leaderboard', '.ad-leaderboard', '.trc_rbox_outer', '.ks-recommended', '.article-da', 'div.sponsored-stories-component', 'div.addthis-smartlayers', 'div.article-adsponsor', 'div.signin-prompt', 'div.article-bumper', 'div.video-placeholder', 'div.top-ad-container', 'div.header-ad', 'div.ad-unit', 'div.demo-block', 'div.OUTBRAIN', 'div.ob-widget', 'div.nwsrm-wrapper', 'div.announcementBar', 'div.partner-resources-block', 'div.arrow-down', 'div.m-ad', 'div.story-interrupt', 'div.taboola-recommended', 'div.ad-cluster-container', 'div.ctx-sidebar', 'div.incognito-modal', '.OUTBRAIN', '.subscribe-button', '.ads9', '.leaderboards', '.GoogleActiveViewElement', '.mpu-container', '.ad-300x600', '.tf-ad-block', '.sidebar-ads-holder-top', '.ads-one', '.FullPageModal__scroller', '.content-ads-holder', '.widget-area', '.social-buttons', '.ac-player-ph', /* Other: */ 'script', 'iframe', 'video', 'aside#sponsored-recommendations', 'aside[role="banner"]', 'aside', 'amp-ad', 'span[id^=ad_is_]', 'div[class*="indianapolis-optin"]', 'div[id^=google_ads_iframe]', 'div[data-google-query-id]', 'section[data-response]', 'ins.adsbygoogle', 'div[data-google-query-id]', 'div[data-test-id="fullPageSignupModal"]', 'div[data-test-id="giftWrap"]' ]; for(let i in selectors) { let nodesList = document.querySelectorAll(selectors[i]); for(let i = 0; i < nodesList.length; i++) { let el = nodesList[i]; if(el && el.parentNode) el.parentNode.removeChild(el); } }})();
It works surprisingly well!
Bookmarklet 15: Site Technology Profiler
Attribuition: This was subitted be @opensourcee on dev.to. Be sure to check him out!
This utilizes a site called w3techs to analyze a URL and determine it's technologies.
Code:
javascript:(function() {
var currentSite = window.location.hostname;
var redirectUrl = "https://w3techs.com/sites/info/" + currentSite;
window.location.href = redirectUrl;
})();
Goodbye for now!
I hope you have enjoyed learning about bookmarklets. In the comments below, share some of your own! I might add them (with attribution, of course).
Oh, and be sure to check out my other posts on DEV, and my portfolio site that I made recently, too!
https://the-best-codes.github.io/
More Bookmarklets: https://the-best-codes.github.io/tools/bookmarks/
Thanks for reading, and happy coding!
Top comments (0)