javascriptbookmarkletasana

asana javascript bookmarklet to create a new task


I'm trying to put together a bookmarklet that can take the current page's URL, title, plus any selected text and then post this as a new task to Asana via the API.

I've created a specific project for these to go in, captured the project id, and have identified the workspace id. Testing these values using curl on the command line works fine:

curl --user MYAPIKEY: https://app.asana.com/api/1.0/workspaces/MYWORKSPACEID/tasks --data-urlencode 'name=Hello World' --data-urlencode 'notes=How are you' --data-urlencode 'projects[0]=MYPROJECTID'

Borrowing from other example javascript bookmarklet's I've put together the following code:

javascript:
apikeyhash='MYBASE64ENCODEDAPIKEYPLUSCOLON';
workspaceid='MYWORKSPACEID';
projectid='MYPROJECTID';
title=document.title;
loc=location.href;
if(document.getSelection) { 
  text=location+'\r\r'+document.getSelection(); }
else {
  text=location;
}
xml = new XMLHttpRequest();
xml.open('POST', 'https://app.asana.com/api/1.0/workspaces/'+workspaceid+'/tasks', false);
xml.setRequestHeader("Authorization", 'Basic '+apikeyhash);
xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xml.send('name='+encodeURIComponent(title)+'&notes='+encodeURIComponent(text)+'&projects%5B0%5D='+projectid);
alert(xml.responseText);

(Where MYBASE64ENCODEDAPIKEYPLUSCOLON is the output from: echo -n 'MYAPIKEY:' | openssl enc -base64)

Using this as bookmarklet (accessed via the bookmark bar in Safari) just results in the current page appearing to refresh, and nothing is added to Asana. I'd appreciate any help in fixing the javascript.

Note: My ideal solution would be to pop up the quick-add-task dialogue from Asana and pre-populate that form (using the credentials of the currently logged on Asana user) but I'm not sure if this is possible. For now simply being able to quickly send the URL, title, plus any selected text to Asana as a new task would be very useful. With only a handful of users, creating custom bookmarklets with each user's API key is acceptable.


Solution

  • I suspect that if you check the javascript console in your browser you'll see that it's rejecting the cross-site request. The Asana API doesn't currently support CORS (though we plan to in future), so the usual rules apply: you can only make requests to the same host:port as the current website.