Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do bookmarklets work regarding cross origin requests - Is cors required?

I know what a bookmarklet is, meaning I know how to create one and that it can access the page that the user is browsing.

What I don't understand is how to send information from that page to my server.

When I make an ajax call to my server from the bookmarklet ( supposing this is possible ), how does it know that the bookmarklet is mine, i.e. not a cross origin request?

Or is this even possible? Am I required to use cors?

Or can I use the bookmarklet with a plain ajax call?

I simply want to get some information from whatever page/domain the user is on, and send it to my server for processing.


1 Answers

how does it know that the bookmarklet is mine, i.e. not a cross origin request?

The server doesn't know. The browser doesn't care. The code and all it does is treated as if it was a native part of the page. (You can tell your server side code anything you want to tell it, but that isn't relevant here.)

Or is this even possible... to get some information from whatever page/domain the user is on, and send it to my server?

If you only need to send data, you can use a regular old POST via a form, or GET via a form or appended script or even an IMG object. To post with a form, create an iframe so the main page's location doesn't change on submission.

If you want to also get data back there is JSONP or AJAX + CORS (specifically the Access-Control-Allow-Origin header). You don't even have to use JSONP in the strictest sense. That is just a standard to pass data. Instead of returning code which makes a single function call with a JSON argument, your server could just as easily return any JavaScript code you wish to execute.

like image 199
DG. Avatar answered Nov 28 '25 09:11

DG.