3

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?

synaptik
  • 8,971
  • 16
  • 71
  • 98
  • 2
    Clicking the bookmark will de-select the text. You'd need to continually capture what's selected. – Diodeus - James MacFarlane Oct 08 '14 at 16:02
  • See: http://stackoverflow.com/questions/21026569/how-to-capture-event-on-text-selection – Diodeus - James MacFarlane Oct 08 '14 at 16:03
  • 1
    You could start by storing the selected text as a variable using `window.getSelection()` although browser compatibility is not very good. I know older versions of IE use `document.selection` and as @Diodeus said, as soon as the user clicks the bookmarklet, the text will become unselected. – APAD1 Oct 08 '14 at 16:03
  • @Diodeus but, [this blog post](http://arcadiamashups.blogspot.com/2009/10/get-selection-bookmarklet-pattern.html) looks like that isn't true. What am I missing? – synaptik Oct 08 '14 at 16:08

2 Answers2

4

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()
user247702
  • 23,641
  • 15
  • 110
  • 157
1

This method will open the url in a new window or tab (depending on browser settings), instead of opening the url in the current tab. So, you won't lose your place. It uses window.open instead of location=

javascript:(function(){s=document.selection?document.selection.createRange().text:window.getSelection?window.getSelection().toString():document.getSelection?document.getSelection():'';if(s==''){s=prompt('You%20did%20not%20select%20any%20text%20to%20search%20for.%20Enter%20the%20text%20to%20search%20for%20:','');}if(s){window.open('https://mxtoolbox.com/SuperTool.aspx?action=ptr%3a'+s,  '_blank')};})()
johny why
  • 2,047
  • 7
  • 27
  • 52