Search code examples
javascriptbookmarklet

Bookmarklet to go to URL based on selected text


How could I write a bookmarklet for Google Chrome that will take the selected text, append it to a predetermined URL, and then go to the modified URL.

For example, let's say the base URL is http://www.mybaseurl.com/. (This base URL is hardcoded in the bookmarklet code.) Now, suppose that on a random webpage I select the text dog. Then, if I click the bookmarklet while that text is selected, I want the bookmarklet to cause the browser to visit the following URL: http://www.mybaseurl.com/dog.

How can this be done?


Solution

  • You can get the currently selected text with window.getSelection(). So this bookmarklet can redirect based on the selected text:

    javascript:window.location.href="http://www.mybaseurl.com/"+window.getSelection()