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.
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 (
Open your browser’s bookmark window, and add a new bookmark:
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.
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
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