How can I send cookies from a bookmarklet XMLHttpRequest which belong to the site being accessed?

StackOverflow https://stackoverflow.com/questions/18388674

  •  26-06-2022
  •  | 
  •  

Question

I'm trying to create a bookmarklet which needs to hit a server (using a POST) to obtain some data. Accessing that data requires that I am logged in, which is kept track of by using cookies. The problem is, my bookmarklet is running in the context of some random web site, and so it can't access the cookies belonging to the site I am trying to hit and in fact it doesn't even send the cookies that belong to that web site.

I have seen some hints that suggest that what I am trying to do is possible, but which are a bit unclear on exactly how this could be accomplished. For instance, in this question, the accepted answer includes this tidbit: "Very often these types of bookmarklets open a small popup for the user which contains a page from the app" but I do not understand how this would accomplish what I am trying to do. I assume it has something to do with the fact that the page itself is in the proper domain and thus can send the required cookies, but I'm not sure how to get data into the page to tell it what I want (I suppose I could do something where I encoded the request in the URL parameters, but then this would show up in the http logs which is not desirable), but more importantly I am not sure how I would get the data back from the window - whenever I try I get an exception "Permission denied to access property 'document'" (or whatever I try to access). I also get the same problem if I use an IFRAME and try to access the parent from the child (or the other way around).

Was it helpful?

Solution

You have asked several quetions.

1.) How can I send cookies from a bookmarklet XMLHttpRequest which belong to the site being accessed?

XMLHttpRequest will send cookies belonging to the domain you are calling. If you want to cross domains you have to enable CORS: http://enable-cors.org/

2.) "Very often these types of bookmarklets open a small popup for the user which contains a page from the app"

This is not about making an XMLHttpRequest. The data goes into the popup via GET. You can even do this via POST but it is slightly more complex. Just search "post to popup" or "post to iframe".

3.) I am not sure how I would get the data back from the window

If the other window/iframe is holding a page from a different domain, use postMessage: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage - this can actually go in both directions and can actually be used to enable complex cross domain communication without CORS.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top