简体   繁体   English

如何防止对JavaScript:URL进行空格编码?

[英]How do I prevent spaces from being URL encoded for a `javascript:` URL?

I'm trying to use the following as a URL that executes javascript: 我正在尝试将以下内容用作执行javascript的URL:

javascript:var field = document.getElementsByName("actions[hide]"); + for (i = 0; i < field.length; i++)field[i].click();

However, the spaces get URL encoded when I bookmark it, replaced with %20 , which (for a reason unknown to me) causes the JS code not to work. 但是,当我将其添加为书签时,空格将获得URL编码,被%20代替(由于我不知道的原因),这将导致JS代码无法正常工作。

javascript:var%20field%20=%20unescape%20document.getElementsByName("actions[hide]");%20+%20for%20(i%20=%200;%20i%20<%20field.length;%20i++)field[i].click();

if you want to create a bookmarklet i would suggest you this site: 如果您想创建一个书签,我建议您访问以下站点:

http://benalman.com/code/test/jquery-run-code-bookmarklet/ http://benalman.com/code/test/jquery-run-code-bookmarklet/

there is written that it is used for jquery code but you can also convert normal javascript with this generator. 上面写着它用于jQuery代码,但您也可以使用此生成器转换普通的javascript。 Or you can simplify use the jquery and convert your code from: 或者,您可以简化使用jquery并将代码转换为:

var field = document.getElementsByName("actions[hide]"); + for (i = 0; i < field.length; i++)field[i].click();

to

$('[name="actions[hide]"]').each(function() { $(this).click(); });

i use this script every time i create a new bookmarklet and i love it 我每次创建新的书签时都会使用此脚本,我喜欢它

EDIT: when you enter your code you must paste it without the "javascript:" text in front. 编辑:当您输入代码时,您必须粘贴它,并且前面没有“ javascript:”文本。

I didn't understand as well the purpose you mean for that javascript as url scheme. 我也不太了解您将javascript用作url方案的目的。
Anyway if you put that string into the browse address bar to work within the current web page, probably it won't. 无论如何,如果您将该字符串放入浏览地址栏中以在当前网页中工作,则可能不会。
You can try to call an anonymous function: 您可以尝试调用匿名函数:

<a href="javascript:(function() { var field = document.getElementsByName('actions[hide]'); for (var i = 0; i < field.length; i++) { field[i].click(); } })();">Click me</a>

Encoding spaces in javascript: URIs shouldn't (and doesn't in my experience) break scripts. 在javascript中对空格进行编码:URI(根据我的经验)不应该破坏脚本。 The problem is most likely your + which is also a special character in URIs (it also means a space) but isn't being automatically converted by the browser as the character is allowed at that point in a URI. 问题很可能是您的+ ,它也是URI中的特殊字符(它也表示空格),但是由于URI允许在该位置使用该字符,因此浏览器不会自动将其转换。

You need to encode the + character as %2B (along with any other special characters you might have in the JS). 您需要将+字符编码为%2B (以及JS中可能包含的任何其他特殊字符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM