Rail, ajax and iframe in Safari

There are some elements in our application that work with ajax. We offer users to embed parts of the application in an iframe.

Everything works fine in Chrome and Mozilla. In Safari, we get error 422, and the server log looks like this:

2015-07-15T08:26:06.818885+00:00 app[web.1]: Completed 422 Unprocessable Entity in 4ms 2015-07-15T08:26:06.815411+00:00 app[web.1]: Can't verify CSRF token authenticity 2015-07-15T08:26:06.823389+00:00 app[web.1]: ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): 

We found that if we directly access the iframe AND THEN URL, which contains the iframe, it is working fine, which may indicate that it is associated with cookies.

I tried this solution , but we still have this problem.

+1
source share
2 answers

Finally, I realized that Safari does not allow cookies to be stored in an iframe.

This means that if you need to use cookies, you need to do something.

I found this solution:

  • In iframe code, check if session[:safari_cookie_fixed] . If not, print the code that will communicate using postMessage to the parent window and tell it that we need a redirect.
  • The parent window sends a signal through postMessage in the iframe when the iframe loads. The listener, which was visualized in the absence of a cookie, sends a signal to the parent to perform the redirect, and the parent redirects to the /set-cookie page in the iframe domain, adding its current url as a parameter to the query string.
  • set_cookie action saves the safari_cookie_fixed cookie and redirects back to the parent page (its URL is available in the query line)

Of course, this solution requires adding some js code to the parent page, but when you give your user iframe html code, you can also include js.

+1
source

Safari (default) does not allow cookies to be set in iFrames if the user has not visited the site already. Imagine this code:

 # a.com <iframe src="b.com/iframe"> 

If you visit b.com directly (on any page) and set a cookie, then Safari will send this cookie when you visit a.com and the iFrame will load into b.com .

However, if you visited a.com without first visiting b.com , then Safari will ignore any cookie that b.com/iframe trying to set.

The description is described here in the Safari Solution section.

  • Determine if cookies are supported.
  • If not, put an inscription on the page saying "This site requires cookies. Click here to continue."
  • When the user clicks on the link / button, open a popup that sets the cookie and closes. On desktop computers, you can make the popup quite small and harmless. On mobile devices, it is uglier, since you cannot make a pop-up window smaller than a full-screen one. However, in any case, a pop-up window is only displayed on the screen in less than a second.
  • iframe reboots and now it can use cookies.
+1
source

All Articles