Cross protocol cookie iFrame

2019-06-13 04:29发布

I have a web page on http://localhost/mySite/Page1.aspx that contains an iframe with src https://localhost/mySite/Page2.aspx.

Inside iframe page (Page2.aspx), i set cookie with JavaScript. How i can read that cookie on parent page (Page1.aspx)??? It looks like Page1 not sees the cookie that Page2 sets.

To set/read cookies, I use jQuery.Cookie plugin:

$.cookie('myKey', JSON.stringify(data), { expires: 1, path: '/', domain: 'localhost' });

BTW, if someone can give me an idea how to transfer data on client in such scheme, i will glad to know about it (Server pooling not a solution for me). I found it works with sessionStorage / localStorage, but it works only in IE :(

2条回答
唯我独甜
2楼-- · 2019-06-13 04:34

I don't think this is completely correct. The cookies for which the secure attribute is not set to true, will be shared across the domain irrespective of the protocol in use.

The real problem for you is the jquery ignoring this aspect, which can be altered by specifying secure=true as a JSON attribute using $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); as in this question.

查看更多
干净又极端
3楼-- · 2019-06-13 04:43

Based on the question's comments:

The issue is due to the Same Origin Policy (SOP), which forbids contents of different sources from interfering with one another. different sources is not only based on the comparison of domains, it is also based on the protocol in use as it is clearly shown on this Wikipedia page. Thus, http://localhost is a different origin to https://localhost.

In order to make these two sources able to communicate:

  • this link perfectly describes the commonly used techniques (iframe proxies & URL polling), and intelligibly sums up the rules of the SOP in its paragraph "The Laws of Physics: what you can do with IFrames"
  • this other well-documented article (linked from the article above) merges the usual techniques into an elegant solution
  • in case the targeted browsers are all HTML5-compliant (i.e. up-to-date-and-to-standards browsers, i.e. not most MSIE versions), this standard introduced a new inter-frame communication system with window.postMessage() and the onMessage event

There are also free pre-built solutions (which I didn't tested though), like Ternarylabs' Porthole or EasyXDM.

Cheers!

查看更多
登录 后发表回答