Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to deal with quotes in bookmarklets

this is a script i found for writing jQuery bookmarklets and i've added three lines of code to it. the problem is jQuery code has lots of quotes (for selectors) and as i have to put the bookmarklets in a href="javascript:code" everything gets messed up with the href's double quotes. here is what my code looks like, i tried to escape double quotes, in many ways, but none did work. is there a 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 function body
but if i run the javascript only(not using an html link) it runs fine.

like image 341
Pouria P Avatar asked Jan 10 '13 14:01

Pouria P


2 Answers

There are a couple ways of doing this, one is to HTML-escape the quotes; &quot; or &#34; for ", &#39; for '.

The other way, my preferred, is to enter the bookmarklet as a string in JavaScript and attach it to the <a> at load time, meaning you don't have any HTML-related problems with it and the browser can do all the encoding for you if you save it.

Also as sbmaxx pointed out, you may need to remove the // comments. This is because a URI is not expected to have any line breaks and therefore the comment would never end when put onto one line.

like image 177
Paul S. Avatar answered Nov 19 '22 02:11

Paul S.


You can not have // comments or line breaks in the attribute. It needs to be one long string.

If you want comments, it needs to be block comments /*foo*/

It needs to look like

<a href="javascript:document.body.style.color='red';alert('no line breaks');void(0);">foo</a>
like image 36
epascarello Avatar answered Nov 19 '22 02:11

epascarello