Cross-Browser Bookmarklets: Stuff You Should Know
Writing cross-browser bookmarklets is an exercise in patience. You may hit a few problems along the way if you don’t know about these things. So here are a few things that could save you some time building those awesome bookmarklets:
Know “your” limits
Well not your limits but those of the worst browser in the world. Every Web Developer I know hates Internet Explorer for a multitude of reasons. Here are a few more reasons to hate it:
Reason #194716
URLs cannot be more than 508 characters; spaces count triple because they must be encoded => %20.
Solution:
Use the ternary operator, use one letter variables for frequently used items and look at using with() to reduce longer namespaces.
Reason #194717
You cannot use prompt() in a bookmarklet. The popup blocker sees it as a threat for your security.
Solution:
Rely on selected text instead of prompts. Tell your users to move on to a better browser out there.
Void any calls that return something
Any function that returns something like a window.open call should be voided. What this means is that the call will not return a value like it usually does to let you know if the action succeeded or not. You see when you have a return value your url changes to that url value. So if your popup opens your page changes to http://true. Not exactly want you had in mind is it?
Solution:
void(window.open(url))
Functions can be stored in variables too
Checking that a functionality exists prior to calling a function is a good way to make something cross-browser while reducing the size of your bookmarklet.
Getting the user’s selected text:
var selection = '';
if (window.getSelection){
selection = window.getSelection();
}else{
selection = document.selection.createRange().text
}
Adding ternary operators to one line this:
var selection = (window.getSelection ? window.getSelection() : document.selection.createRange().text);
And finally using a single character variable name to store it to make it even shorter:
var g = window.getSelection, s = (g ? g() : document.selection.createRange().text);
Happy coding!
