In this article, we are going to see how quick and easy it is to concoct a bookmarklet by creating one that performs a Wikiwand (better-looking Wikipedia) search for a selected text on any web page.
How bookmarklets work
The URI of a bookmarklet uses the
The URL structure Wikiwand uses for an English-language article is
https://www.wikiwand.com/en/articleTitle. We need to write a script that jumps to the Wikiwand page of which URL ends with the string the user has just selected — the selected text will need to be put in place of
First, we get hold of the text the user has selected on the page with the following code:
Next, we need to perform a visit to the Wikiwand article page. We’ll achieve this by using the following logic, where
newURL will be the URL of the Wikiwand article page (that will contain the selected string at the end):
location.href = newURL
When we put these two code snippets together, we end up with the following script:
Now we only have to add the
replace(/\n/g,'%20') at the end replaces any new line character (
\n) in the text with a single space character (
Create the bookmark
Open your browser’s bookmark window, and add a new bookmark:
- Firefox: Press ctrl + shift + B / cmd + shift + B, right-click "Bookmarks Toolbar", and select "New Bookmark".
- Chrome: Press ctrl + shift + O / cmd + alt + B, right-click "Bookmarks bar", and select "Add Page…".
Rather than reaching for the bookmarks menu every time you need the bookmarklet, you can choose to display it directly in your browser for quick access.
- Firefox: Click "View > Toolbars" in the top menu bar, and select "Bookmarks Toolbar".
- Chrome: Press ctrl + shift + B / cmd + shift + B.
Create a bookmarklet link
You can add your bookmarklet to a website as a hyperlink as well, which visitors can bookmark by either simply drag-and-dropping the link to the bookmark toolbar, or right-clicking the link and selecting the option to bookmark it.
To turn your bookmarklet into a hyperlink, create an
<a> HTML tag with the bookmarklet script as the value of its
How to store bookmarklets separately
href attribute in the HTML file):
The code snippet above is wrapped in a self invoking arrow function, and uses features of ECMAScript 6, such as the
let keyword, in order to reduce code length. It adds a
<script> tag pointing to the
myscript.js file to the
<head> section of the document when the user clicks the bookmarklet (note that you may need to use an absolute path for the