How to get and set item by localStorage in iframe - javascript

I have two webpage with different hostname, the hostname of webpage A is 'a.b.info' and the other is 'c.d.com', for example. Now I want to hybird the webpage B into the webpage A by iframe, that is to say the attribute src of the iframe is 'c.d.com'.I used localStorage in website B, when I open 'a.b.info' in Chrome Incognito Window, the webpage B threw out an exception:
DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
It will only happen in an Incognito Window in Chrome. please tell me how to deal with this exception?

I don't think you can directly access properties like localStorage, cookies, or sessionStorage across domains.
However you can hack around this. You would need to setup some message communication such that webpage A and B can send messages to each other. In those messages, you can include raw string data which can include your localStorage data. ( I don't think it is a very secure thing to do, specially if you are sharing secrets or some sort of auth data)
Have a look at this example:
https://gist.github.com/pbojinov/8965299

Related

Cannot get reference to one page from another

I am working on a web app that needs to have two parts. The one is a controller and the other is a display. Something like Google Slides in presentation mode. The controller has a button to launch the display:
<script language="JavaScript">
function OpenMain()
{
var MainPage = window.open("TheUltraSignalLite.html");
TimerIMG = MainPage.document.getElementById("TimerIMG");
TimerIMG.src = "TM-Full-Blue.jpg";
}
</Script>
The call to window.open seems to return null. I have tried Chrome, Edge, Firefox, and Opera and they all have the result. These are all local files for now, but I might put in on a web server someday. I have seen some answers that want you to turn off security, but I cannot ask everyone who uses this app to turn off security. How do I get a valid reference to the display window?
Edit 1:
Yes, window.open from the local disk does cause a CORS restriction.
I tried this where both files are in the same AWS S3 Bucket, so the CORS should not be an issue. But I still get a null on the window.open. If I put a breakpoint on the first line, then everything worked. If I split the open and the rest of the code into two functions with two buttons, it works. So it looks like I have to find a way to run the open in an async way.
Edit 2
My solution to keep it simple was to put the window.open in the OnLoad event. This opens the child window and allows it to fully render and the value of MainPage is ready to use. (I changed the MainPage to a global variable.) I still have to run it from some type of web server, rather than loacl file, but that is not a big deal.
If you are not allowed to access the new window content, then the problem you are encountering is a basic security feature of web browsers. Citing mdn:
The returned reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements
To read more about Same-origin policy
If your new window respects the Same-origin policy, then you can access the content of the new window with for example:
// Open index.html from the current origin
const newWindow = window.open('index.html')
const h1 = newWindow.document.querySelector('h1')
If you want to avoid asking users for pop-up permission, then you should probably use a link instead of a pop-up.

Why is same-origin-policy blocking this javascript call on a local domain?

I've got a local dev site running on http://mysite.local/
(it's a Django admin site with Grappelli installed, if that's any relevance).
The admin site opens a popup window for some operations (i.e. via showRelatedObjectLookupPopup())
Due to previous similar issues with same-origin-policy (in production, the admin site loads some URLs from a CDN domain, which can trigger it) we have a "normaliser" JS function that explicitly sets:
document.domain = "mysite.local";
Both in the parent and in the popup, on page load.
The popup contains a link with an onclick handler that triggers a JS function in the parent:
onclick="opener.dismissRelatedLookupPopup(window, '422'); return false;"
Clicking this link in Chrome or FF results in a similar browser error:
Permission denied to access property "dismissRelatedLookupPopup" on
cross-origin object
or
Blocked a frame with origin "http://mysite.local" from accessing a
cross-origin frame.
Both the popup and the opener URLs share the same protocol, domain and port.
This is only an issue on the local domain. On dev/uat/production sites, (i.e. dev.mysite.com), all of which have their domain set to the superdomain "mysite.com" by the above "normaliser" function, the popup can successfully call the JS function in the parent.
What's stopping it on the local domain? What have I missed?
It seems that switching the local domain, as per the original suggestion from #charlietfl, has indeed fixed the issue. It now runs locally as local.mysite.com instead of mysite.local, and the same-origin error has gone. I'm still unclear on what was triggering the error (was it because the the domain had only two parts as opposed to three? Was it something specific to domains ending in ".local"?) but in the unlikely event that anyone else trips up on this, that's what fixed it for me.

Same Origin issue accessing iframe from jQuery in browser console

I'm trying to automate interactions with a website that I don't control. Notably for this discussion, the page from the site contains several iframes. For example, consider the source of the imaginary (but comparable) page https://www.chicken.com/a/b/hamburger.aspx to look something like:
<html>
...
<iframe id="iframe_a" src="meatloaf.aspx"></iframe>
<iframe id="iframe_b" src="stuffing.aspx"></iframe>
...
</html>
Notably, the 'src' attributes of the iframes are relative, so they are to be loaded from the original domain (www.chicken.com/a/b/ in this case) and there doesn't seem to be any 'Same Origin' issues, since I can login to the site and interact with it just fine. However, this all changes when I try to interact with the iframes using the Chrome dev console. For instance, this is what happens when I try to get the contents of one of the iframes using jQuery:
$('#iframe_a').contents()
jquery-1.11.3.min.js:2 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "https://www.chicken.com" from accessing a cross-origin frame.(…)
My (wrong) intuition is that since the sources of these iframes is the same domain as is the original page, that javascript interactions in the console should be under the auspices of that original domain, and everything should be fine. But clearly I'm not understanding the nuances of Same Origin. Can someone enlighten me about how it works in this case? And perhaps suggest a way to manipulate the contents of this iframe from a running browser?

Firefox localstorage from iframge - SecurityError: The operation is insecure

I have 2 subdomains:
www.example.com = For logged in users only
internal.example.com = Public website
Since I use localstorage to store some informations on internal.example.com which I need on www.example.com I had implemented the following solution:
I load on www an iframe located on internal. I set on both sides the document domain value to the "parent domain"
document.domain = "example.com";
Now on www, I can access the localStorage of internal over www by doing the following:
frames['internalFrameName'].window.localStorage;
Now I can read and write values. This works in Chrome and Internetexplorer, and it worked in Firefox until the last update to FF30. Now I get the error:
SecurityError: The operation is insecure.
Any ideas how to fix it?
You could use a messaging system to communicate between the both frames. Then the iframe can just send you the local storage data.
This might help you with that: How to communicate between iframe and the parent site?
You need to use frames['internalFrameName'].postMessage(message, targetOrigin, [transfer]);
Gecko throws the error message when cookies are disabled so besides the object detection for localStorage (which I'm sure you're doing in the code you didn't post) first check for support for cookies.
Change:
if (window.localStorage)
To:
if (document.cookie && window.localStorage)

Permission issues checking if parent site is my parent domain within iframe

I've read several of the questions on this but am still a little confused.
For example: OK, I can't post examples because of hyperlink limitations
Here is my exact situation.
I have a site at mydomain.com
One of the pages has an iframe to another page at sub.mydomain.com
I am trying to prepare an onload script that if the page is not in an iframe or the parent domain of the page containing the iframe is not mydomain.com then redirect to mydomain.com.
After the initial permission issues I realised the problem with sub domains counting as separate domains.
One of the posts above says that "could each use either foo.mydomain.com or just mydomain.com"
So I tried (for testing):
onload="document.domain='mydomain.com';alert(parent.location.href);"
This produced the error (http replaced with lar
Error: Permission denied for <http://sub.mydomain.net> (document.domain=<http://mydomain.net>) to get property Location.href from <http://mydomain.net> (document.domain has not been set).
Source File: http://sub.mydomain.net/?pageID=1&framed=1
Line: 1
Removing the alert produces no errors.
Maybe I am going about this the wrong way since I do not need to interact with the parent just read its domain if there is one.
A nice simple top.domain. For read only there must be a way so that people can prevent their own pages being used within other people's sites.
You can't (easily) do this because of security restrictions.
This answer from #2771397 might point you in the right direction.
OK, while looking at the error console I still had open when I got home a wee lightbulb lit up. I am pretty new to javascript (can you tell ;) but I thought "If it has try/catch"...
well here is a hack at least to get the name of the top domain and an example of how I will use it in my site to show content only if the page is a frame in the correct domain.
Firstly the header will have the following partially PHP generated function:
function getParentDomain()
{
try
{
var wibble=top.location.href;
}
catch(err)
{
if (err.message.indexOf('http://mydomain.com')!=-1)
{
createCookie('IAmAWomble','value')
}
}
}
Basically the value will be something based on the PHP session I think. This will be executed at page load.
If the page is not within the proper site or if javascript is not enabled then the cookie will not be created.
PHP will then attempt to read the correct value from the cookie and show the content or an error message as appropriate.
I do see a slight flaw in this for first visit since page load will run after PHP has generated the content but I'm sure I can work around this somehow. I thought I'd post because this is at least what I was initially asking for and that is a way to read the URL of a parent site if it is in a different domain to the site in the frame.
IIUC you want to use the window.parent attribute: “A reference to the parent of the current window or subframe.”
Assumably, window.parent.document.location.host contains the container page URL domain name.

Categories