What is/are the generally accepted design patterns for Javascript bookmarklets?
Is it best to insert an iFrame and do whatever needs to be done in there, so as to not clutter the page with your extra 开发者_运维技巧scripts, CSS styles, etc? How do you detect that things are complete and remove the iFrame when you can't talk between the main window and the iFrame?
Is it acceptable to insert scripts/CSS into the DOM and do your work there?
My main example is the Instapaper bookmarklet, which uses an iFrame and closes it when it's all done.
All the bookmarklets i have ever done are directly inserted into the DOM of the main page. All the code has lived inside a namespace for that bookmarklet so the DOM pollution is kept at a minimum, and of course there are checks to make sure there are no collisions with existing variable names.
The reason for insertion into the DOM of the main document is because it makes everything easier - there is rarely any good reason to make it harder on yourself than it has to be :)
But of course this depends on your goals.
Pattern 1:
javascript:void(document.title += 'HAI!')
any bookmarklet return value gets converted toString and act as it was passed to document.write
void
operator prevents it
Pattern 2:
javascript:(function(){ for ( var i = 0; i < document.images.length; i++ ) document.images[i].title = document.images[i].alt; })()
bookmarklets are running in the global scope, so without anonymous function code above will "leak" loop counter as window.i
精彩评论