Reputation: 13744
I am attempting to make a bookmarklet that will load up the Hacker News discussion for the page I'm on, if it exists.
Here's the code, as I have it to run in node.js's REPL:
// node.js stuff
require.paths.unshift('.');
var sys = require('util');
var alert = sys.puts;
var XMLHttpRequest = require("XMLHttpRequest").XMLHttpRequest;
//javascript: (function () {
//url = 'http://api.ihackernews.com/getid?url=' + encodeURIComponent(window.location.href);
url = 'http://api.ihackernews.com/getid?url=' + encodeURIComponent('http://blog.asmartbear.com/self-doubt-fraud.html');
http = new XMLHttpRequest();
http.open("GET", url, true);
http.onreadystatechange = (function () {
if (this.readyState == 4) {
alert('foo');
var ids = eval('(' + this.responseText + ')');
if (ids.length > 0) {
ids.reverse();
//window.href = ids[0];
alert(ids[0]);
} else {
alert('No stories found.');
}
}
});
http.send();
//})();
This works as expected. (It makes use of a little file to simulate XMLHttpRequest in node.)
Uncommenting the function definition lines (and removing the other node-js stuff) gives me a nice little one-liner, once packed:
javascript:(function(){url='http://api.ihackernews.com/getid?url='+encodeURIComponent(window.location.href);http=new XMLHttpRequest();http.open("GET",url,true);http.onreadystatechange=(function(){if(this.readyState==4){alert('foo');var ids=eval('('+this.responseText+')');if(ids.length>0){window.href=ids[0]}else{alert('No stories found.')}}});http.send()})();
Running it, however, prompts Firefox's error console to give me the incredibly helpful message "syntax error", followed by a "()" an an error pointing to right after the second parenthesis.
I'm not using Firebug because its nightly and Firefox's nightly don't want to cooperate at the moment.
The solution to this will probably come to me soon (normally I figure it out from the process of explaining everything in this text box), but I suppose I'd appreciate any help on this. It's really bothering me. :/
Upvotes: 1
Views: 468
Reputation: 630589
It's because your response being blank (due to the same origin policy) is basically executing this:
eval('()'); //SyntaxError: Unexpected token )
You need to add a check if there's a response at all, like this:
http.onreadystatechange = (function () {
if (this.readyState == 4) {
if(this.responseText) { //was the response empty?
var ids = eval('(' + this.responseText + ')');
if (ids.length > 0) {
ids.reverse();
window.href = ids[0];
}
} else {
alert('No stories found.');
}
}
});
Upvotes: 3