views:

70

answers:

4

Just curious if anyone can explain to me why I can request a page from a bookmarklet like this one:

javascript:var%20s=document.createElement('script');var data=encodeURI(location.href)+encodeURI('\n\n')+(encodeURI(document.getElementsByTagName('body')[0].innerHTML));s.setAttribute('src','http://example.com/remote.php?id=68&act=new&data='+data);document.getElementsByTagName('body')[0].appendChild(s);void(s);

Which goes out and request a page and can even provides GET-variable input.

However, I can't make a post/get XHR with ajax through something like jQuery due to same origin policy... Why? Is this a browser issue or part of standards?

note: I changed the bookmarklet. Note 2: My question is why isn't this a violation of policy?

+2  A: 

The difference is that you cannot (directly) read the response that becomes the <script> element.

If the URL happens to return Javascript that defines useful functions, you can use it.
If it contains anything else (such as JSON or XML data), you cannot read the response.

Similarly, you can make an <img> element that points to an image in a different domain.

SLaks
+1  A: 

This bookmarklet isn't violating the same origin policy. Only XHTTP requests are limited by this policy, and this bookmarklet is adding a script element to the page.

DOM Elements (such as images and scripts) are free to fetch resources from anywhere on the internet.

While any script can effectively execute a GET request cross-domain by constructing script or img requests via the DOM, it will be unable to extract any data from that resource unless the returned response is formed appropriately. An appropriately formed response is actually the basis for cross-domain ajax.

altCognito
A: 

That bookmarklet doesn't xhr-request something from another server, but appends a script from that other server, which is acceptable and doesn't conflict with the same origin policy.

Actually this is the known workaround to do this kind of cross server communication, take a look at jsonp.

aularon
+1  A: 

Same Origin Policy for javascript doesn't let pages from different domains to communicate, access each other objects, whether to read or to write, it also doesn't allow xmlhttprequests (ajax calls) to request data from other servers.

But, however, it has nothing to do with allowing scripts referenced on another servers. As @SLaks said, you can add a <script> tag from another server, as you can add <img> tag from another server.

aularon