Is is possible to make ajax calls from a bookmarklet?
I plan to create a bookmarklet which users will use to share content (bacially url's and page title) around the web on say mysite.com. So this is what I am following till now:
- Bookmarklet calls an external.js which basically contains all the logic
- external.js can either a) create an iframe or b) open a popup window and pass in the shared url information
Now my question is... is there a possible third approach where the external js file can load everything via ajax from mysite.com. Or since the bookmarklet will share content from other sites this won't work because of same origin policy. And the only way this could work is by making ajax calls from inside the iframe or popup window?
Also is there a preference or downsides for using the popup window vs. iframe 开发者_如何学编程approach?
Take a look at the approach used by the 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 in fact use JSONP and insert a script tag on the page.
Your bookmarklet will run in the context of the current page, not your site. So, XHR calls to your site will fail.
In general, an iframe will work better than a popup because of popup blockers.
There are some other clever approaches you can take. Consider a JSONP model. Or, if you only need one way communication (ie, send some data to your site), and you don't care about a response, consider loading a GET request URL as the source of an image. You could even stream back a success or failure image if you wanted to get really fancy.
<img src="http://me.com/AddLink?UserId=123&url=http://you.com&title=Your+Site" />
精彩评论