How to prevent bookmarklet from loading its result?

筅森魡賤 提交于 2019-12-20 07:37:52

问题


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);

回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/13796004/how-to-prevent-bookmarklet-from-loading-its-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!