Reputation: 841
I have a simple bookmarklet for presenting in a prompt() the value of a meta element. It works, but after running the window loads either just the string "null" or the prompted value.
How do I prevent the bookmarklet from causing a page load?
I just want the script to pop the prompt but do nothing more.
My bookmarket is this:
javascript:var%20description;var%20metas=document.getElementsByTagName('meta');for(var%20x=0,y=metas.length;x<y;x++){if(metas[x].name.toLowerCase()=="description"){description=metas[x];}}prompt("Meta%20Description",description.content);
.. which unwrapped looks like this:
var description;
var metas=document.getElementsByTagName('meta');
for(var x=0,y=metas.length;x<y;x++){
if(metas[x].name.toLowerCase()=="description"){
description=metas[x];
}
}
prompt("Meta Description",description.content);
Upvotes: 3
Views: 601
Reputation: 3517
The accepted way these days is to wrap your code in an "immediately invoked function expression" like this
(function(){ /*your code */})();
This is better than adding void(0);
at the end because wrapping your code in a function prevents conflicts between named variable and function in your bookmarklet and in those in the scope of the parent HTML document.
In other words, if you run your bookmarklet as it is now on a web page that uses JavaScript code with an already existing variable "description", you could create problems.
Upvotes: 7
Reputation: 97717
Add void(0);
at the end of it.
javascript:var%20description;var%20metas=document.getElementsByTagName('meta');for(var%20x=0,y=metas.length;x<y;x++){if(metas[x].name.toLowerCase()=="description"){description=metas[x];}}prompt("Meta%20Description",description.content);void(0);
Upvotes: 2