In a nutshell, bookmarklets are small little applications you can place as browser’s bookmark bar and they each… Read more
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 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 articleTitle .
First, we get hold of the text the user has selected on the page with the following code:getSelection().toString()
We need to cast the object returned by getSelection() as a string by using the toString() method, in order to make it output the selected text .
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:location.href=
The optional replace(/\n/g,'%20') at the end replaces any new line character ( \n ) in the text with a single space character ( %20 ).
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 href attribute :<!-- add in one line without line breaks -->
Wikiwand Search Bookmarklet
</a> How to store bookmarklets separately
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 myscript.js file).