Reputation: 9539
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?
Upvotes: 5
Views: 3107
Reputation: 2221
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')};})()
Upvotes: 1
Reputation: 24232
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()
Upvotes: 5