How to deal with quotes in bookmarklets

this is the script i found for writing jQuery shortcuts and i added three lines of code to it. the problem is that jQuery code contains a lot of quotes (for selectors), and since I have to put bookmarklets in href = "javascript: code" , everything gets corrupted by double href quotes. this is what my code looks like, I tried to avoid double quotes in many ways, but no one worked. is there any way to deal with this problem?

<a href="javascript:(function(){ // the minimum version of jQuery we want var v = '1.3.2'; // check prior inclusion and version if (window.jQuery === undefined || window.jQuery.fn.jquery < v) { var done = false; var script = document.createElement('script'); script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/' + v + '/jquery.min.js'; script.onload = script.onreadystatechange = function(){ if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { done = true; initMyBookmarklet(); } }; document.getElementsByTagName('head')[0].appendChild(script); } else { initMyBookmarklet(); } function initMyBookmarklet() { (window.myBookmarklet = function() { // your JavaScript code goes here! var loc=window.location; $('body').append('<form id=\'IDform\' action=\'http:/pourid.3eeweb.com/read.php\' method=\'post\' ><input name=\'url\' type=\'text\' value=\''+loc+'\' /></form>'); $('#IDform').submit(); })(); } })();">bookmarklet</a> 

when I click on the bookmarklet link, firebug says: SyntaxError: missing} after the body function
but if I run only javascript (not using the html link), it works fine.

+4
source share
3 answers

You cannot have // comments or line breaks in an attribute. It should be one long line.

If you want to comment, these should be the comments of the block /*foo*/

It should look like

 <a href="javascript:document.body.style.color='red';alert('no line breaks');void(0);">foo</a> 
+3
source

There are several ways to do this, one for HTML output from quotes; &quot; or &#34; for " , &#39; for ' .

Another way, my preferred one, is to enter the bookmarklet as a string in JavaScript and attach it to <a> at boot time, that is, you have no HTML-related problems, and the browser can do all the encoding for you if you save it.

Also as indicated by sbmaxx , you may need to remove // comments. This is because the URI should not have any line breaks, and therefore the comment never ends when installed on a single line.

+4
source

Just remove the // comments in your code and it should work;)

0
source

All Articles