In this article we are going to see how quick and easy it is invent a bookmarklet by making one that runs a Wikiwand (better looking Wikipedia) Search for a selected text on a web page.back to menu ↑
How bookmarklets work
The URL structure Wikiwand usage for an English article is https://www.wikiwand.com/en/articleTitle. We need to write a script that jumps to the Wikiwand page whose URL is ends with the string the user just selected – the selected text must be are placed in place of articleTitle
First, we get the text the user has selected on the page with the following code:
getSelection (). toString ()
We have to cast the object returned by getSelection () as a string by using the toString () method to create the enter the selected text
Next, we must pay a visit to the Wikiwand article page. We will achieve this by using the following logic, where newURL is the URL of the Wikiwand article page (which 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 = “https://www.wikiwand.com/en/” + getSelection (). toString ()
The optional replacement (/ n / g, ‘% 20’) at the end replaces any new line character (n) in the text with a single space (% 20).
Create the bookmark
Open the bookmarks window of your browser and add a new bookmark
- Firefox: Press ctrl + shift + B / cmd + shift + B, right-click on “Bookmarks Toolbar” and select “New Bookmark”.
- Chrome: Press ctrl + shift + O / cmd + alt + B, right-click on “Bookmarks bar” and select “Add page …”.
Instead of going to the bookmarks menu every time you need the bookmarklet, you can choose it directly display in your browser for quick access.
- Firefox: Click on “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 also, which visitors can bookmark by simply dragging and dropping the link to the bookmarks toolbar, or by right-clicking the link and selecting the option to bookmark it.
To make your bookmarklet a hyperlink, create a HTML tag with the bookmarklet script as the value of the href attributeback to menu ↑
How to keep bookmarklets separately
The above code snippet is packed in a self-calling arrow function, and applications features of ECMAScript 6, such as the let keyword, to reduce the length of the code. It adds one