如何防止bookmarklet加载其结果? [英] How to prevent bookmarklet from loading its result?
问题描述
我有一个简单的书签,用于在提示符()中显示元素的值。它可以工作,但在运行窗口后只加载字符串null或提示值。
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.
如何防止书签导致页面加载?
我只想让脚本弹出提示,但不做更多。
I just want the script to pop the prompt but do nothing more.
我的bookmarket是这样的:
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);
推荐答案
这些天被接受的方式是将你的代码包装好像这样的立即调用的函数表达式
The accepted way these days is to wrap your code in an "immediately invoked function expression" like this
(function(){ /*your code */})();
这比添加 void(0); $ c $更好c>最后因为将代码包装在函数中可以防止在书签中和父HTML文档范围内的命名变量和函数之间发生冲突。
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换句话说,如果您现在在使用具有已存在变量description的JavaScript代码的网页上运行书签,则可能会产生问题。
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.
这篇关于如何防止bookmarklet加载其结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!