Javascript Bookmarklet If-Else

Javascript Bookmarklet If-Else

本文关键字:If-Else Bookmarklet Javascript      更新时间:2023-09-26

我正在尝试编写一个bookmarklet来检测用户是否在已经解析的页面上,如果他不是,则应该将值传递给API。

if (window.location.indexOf("thequeue.org") >= 0) {
    alert("Drag the Bookmarklet in your Brookmarks Bar!");
} else {
    location.href = 'http://thequeue.org/r?id=' + encodeURIComponent(location.href) + '&title=' + document.title;
}

一般来说,关于bookmarklet的教程很少,但我找到了这个转换工具:http://jasonmillerdesign.com/Free_Stuff/Instant_Bookmarklet_Converter,它给了我这个:

javascript:(function(){if(window.location.indexOf(%22queue.org%22)%20%3E%3D%200)%0A%20%20%20%20%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20alert(%22your%20url%20contains%20the%20name%20franky%22)%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%20else%20%7B%0Alocation.href%3D'http%3A%2F%2Fthequeue.org%2Fr%3Fid%3D'%2BencodeURIComponent(location.href)%2B'%26title%3D'%2Bdocument.title%3B%0A%7D}());

然而,bookmarklet完全停止工作。我可以确认这是有效的:javascript:location.href='http://thequeue.org/r?id='+encodeURIComponent(location.href)+'&title='+document.title;

我做错了什么?

这应该可以为您工作:

javascript:(function(){if(location.href.indexOf("thequeue.org/")>=0){alert("Drag the Bookmarklet in your Brookmarks Bar!");}else{location.href='http://thequeue.org/r?id='+encodeURIComponent(location.href)+'&title='+document.title;}})();

注意,我稍微改变了if句子,使它更健壮。

您可能想先尝试去掉所有空白。我不知道这是不是你的问题,但它至少会让你的书签不那么难看。