Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent bookmarklet from loading its result?

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);
like image 445
Erics Avatar asked Dec 21 '25 05:12

Erics


2 Answers

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.

like image 57
DG. Avatar answered Dec 22 '25 19:12

DG.


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);
like image 41
Musa Avatar answered Dec 22 '25 18:12

Musa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!