Is it possible to make ajax calls from a bookmarklet?

I plan to create a bookmarklet that users will use to share content (bacially url and page title) on the Internet, for example, mysite.com. So this is what I'm following so far:

  • Bookmarklet calls external.js, which basically contains all the logic
  • external.js can either a) create an iframe, or b) open a popup window and pass information about the shared URL

Now my question is ... is there a possible third approach where an external js file can download everything via ajax from mysite.com. Or, since the bookmarklet will exchange content from other sites, this will not work due to the same origin policy. And the only way this can work is to make ajax calls from inside an iframe or popup?

Also, are there any preferences or disadvantages for using a popup or iframe method?

+6
javascript ajax bookmarklet
source share
2 answers

Take a look at the approach used by Instapaper.com bookmarklet:

javascript:function iprl5(){ var d=document, z=d.createElement('scr'+'ipt'), b=d.body, l=d.location; try{ if(!b)throw(0); d.title='(Saving...)'+d.title; z.setAttribute('src',l.protocol+'//www.instapaper.com/j/xxxxxxxx?u='+encodeURIComponent(l.href)+'&t='+(new Date().getTime())); b.appendChild(z); } catch(e) { alert('Please wait until the page has loaded.'); } } iprl5(); void(0) 

They actually use JSONP and insert a script tag on the page.

+4
source share

Your bookmarklet will be launched in the context of the current page, not your site. Therefore, XHR calls to your site will fail.

In general, an iframe will work better than a pop-up because of pop-up blockers.

There are other smart approaches you can take. Consider the JSONP model. Or, if you only need one-way communication (i.e., sending some data to your website) and you don’t need an answer, try downloading the GET request URL as the image source. You could even convey a reverse or unsuccessful image if you want to get really fantasy.

 <img src="http://me.com/AddLink?UserId=123&url=http://you.com&title=Your+Site" /> 
+1
source share

All Articles