Reading window.location after setting document.domain in IE(6) - javascript

I've got a situation a page on where a script on www.example.com/index.html opens home.example.com/foo.html in a popup window. When the user closes the popup, I want to notify the opener page by calling a Javascript function on it (which does a few things with the DOM). I use unbeforeunload like this:
// In index.html on www.example.com:
window.fn = function () { /* Perform stuff after foo.html has closed */ }
// In foo.html on home.example.com:
window.onbeforeunload = function () {
if (window.opener && window.opener.fn)
window.opener.fn();
};
This doesn't work because the web pages are on different domains. I can set the document.domain property to overcome this:
document.domain = "example.com";
Unfortunately, this doesn't play well with the web app framework I use on the foo.html side (Apache Wicket), as it includes a script which does something like this:
var src = (window.location.protocol == 'https:') ? something : other;
Apparently, in IE6*, when you set the document domain, the location object becomes write-only, and so trying to read window.location.protocol throws "Access denied".
So, my question is: How do I allow cross-domain Javascript function calls while still allowing my scripts to read the contents of the location object?
I can't go via the server. (The work performed by the function I want to call doesn't really play that way.)
I can't read the window.location.protocol property before setting document.domain and then use that value in the conditional assignment; doing so would require me to rebuild the web framework libraries - not something I want to do.
* Possibly in other versions of IE, too; haven't checked.

Can you use jQuery? There's a nice plugin that allows you to do window.postMessage through an iframe in IE 6-8: http://benalman.com/code/test/js-jquery-postmessage/
You could open your popup from the iframe and pass your object between iframe and parent with postMessage.

I can't read the
window.location.protocol property
before setting document.domain and
then use that value in the conditional
assignment; doing so would require me
to rebuild the web framework libraries
- not something I want to do.
can't you read window.location.protocol prior to to setting document.domain and set window.location.protocol once it becomes write-only? Would that require a a rebuild of framework as well? it is a hack but so is IE.

Related

Is it possible to use a Chrome Extension to change document.referrer?

I want my extension to change the document.referrer of certain webpages, but searching for this leads to documentation on how to change the Referrer in the HTTP request headers.
Is there any way to use an extension to change document.referrer, preferably before the javascript(s) of a webpage loads?
Currently I refresh pages where I want the document.referrer altered with window.location.replace(window.location.href), but this generates a noticeable flicker, and only can change the referrer to the current page.
override.js:
Object.defineProperty(Document.prototype, 'referrer', {
get() {
return 'foo';
},
});
This should be put in page context at document_start, there are several methods.
For ManifestV3 the most reliable method is registerContentScripts: example. Specify the correct pattern in matches and optionally add allFrames: true; matchOriginAsFallback: true if the site uses frames.
Note that due to a bug in Chrome the sites can extract the original getter and call it on the main document to get the real referrer. The workarounds are mentioned in the report and aren't simple.

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.

Change window location href in subdomain iframe

I have a.example.com and b.example.com;
When I put b.example.com/foo as iframe in a.example.com:
<iframe src='b.example.com/foo'></iframe>`
the window.location.href value accessible from b.example.com is ... a.example.com/foo (??)...
The problem is - I use an external library in b.example.com/foo that checks for window.location.href and it gets incorrect information.
For this scenario it appears to me that I should iframe /foo content on a completely different domain like:
anotherexample.com/foo, where the window.location.href would actually point to anotherexample.com/foo.
How can I force window object in iframe to actually use its subdomain instead of parent domain with added parameter?
Are you sure you are using your script in the right subdomain? it seems your external library is accessing parent window using window.parent.location, here is a code to check if a page is loaded directly or within another page:
var is_loaded_directly = (window.location == window.parent.location);
Since this code works, something is wrong on your setup or library.
Note: maybe you can solve your issue by checking document.location instead of window.location.

transferring localstorage to another website [duplicate]

I am attempting to share data across subdomains using Safari. I would like to use an HTML5 database (specifically localStorage as my data is nothing but key-value pairs).
However, it seems as though data stored to example.com can not be accessed from sub.example.com (or vice versa). Is there any way to share a single database in this situation?
Update 2016
This library from Zendesk worked for me.
Sample:
Hub
// Config s.t. subdomains can get, but only the root domain can set and del
CrossStorageHub.init([
{origin: /\.example.com$/, allow: ['get']},
{origin: /:\/\/(www\.)?example.com$/, allow: ['get', 'set', 'del']}
]);
Note the $ for matching the end of the string. The regular expression in the above example will match origins such as valid.example.com, but not invalid.example.com.malicious.com.
Client
var storage = new CrossStorageClient('https://store.example.com/hub.html');
storage.onConnect().then(function() {
return storage.set('newKey', 'foobar');
}).then(function() {
return storage.get('existingKey', 'newKey');
}).then(function(res) {
console.log(res.length); // 2
}).catch(function(err) {
// Handle error
});
Check https://stackoverflow.com/a/39788742/5064633
There is simple way to use cross-domain anything, just create simple page that will be included as proxy iframe hosted on domain you try to access, send PostMessage to that iframe and inside iframe you do your LocalStorage database manipulation. Here is a link to article that do this with lcoalStorage. And here is demo that send message to different page in subdomain check the source code, it use iframe and PostMessage.
EDIT: New version of sysend.js library (used by above demo) use BroadcastChannel if browser support it, but still it require Iframe. Recent version also simplify using of Cross-Origin messages, you have html of the iframe in repo, that you can use (or you can use simple html file with single script tag with the lib) and in parent you just need to call one function sysend.proxy('https://example.com'); where example.com need to have proxy.html file (you can also use your own filename and different path).
Google Chrome blocks localStoage access from an iFrame in another domain by default,unless 3rd party cookie is enabled and so does Safari on iPhone...the only solution seems to be opening the parent domain on a different domain and then sending to to the Child via window.postMessage but looks ugly and shifty on phones...
Yes. This is how:
For sharing between subdomains of a given superdomain (e.g. foo.example.com vs bar.example.com vs example.com), there's a technique you can use in that situation. It can be applied to localStorage, IndexedDB, SharedWorker, BroadcastChannel, etc, all of which offer shared functionality between same-origin pages, but for some reason don't respect any modification to document.domain that would let them use the superdomain as their origin directly.
NOTE: This technique depends on setting document.domain to allow direct communication between iframes on different subdomains. That functionality has now been deprecated. (As of April 2021 it continues to work in all major browsers however. From Chrome v109 the feature will be disabled unless an Origin-Agent-Cluster: ?0 header is also sent.)
NOTE: Be aware that this technique removes the same-origin defences that block malicious script on a subdomain from affecting the main-domain window, or visa versa, potentially broadening the attack surface for XSS attacks. There are other security implications for shared hosting as well - see the MDN document.domain page for details.
(1) Pick one "main" domain to for the data to belong to: i.e. either https://foo.example.com or https://bar.example.com or https://example.com will hold your localStorage data. Let's say you pick https://example.com.
(2) Use localStorage normally for that chosen domain's pages.
(3) On all other https://*.example.com pages (the other domains), use JavaScript to set document.domain = "example.com"; (always the superdomain). Then also create a hidden <iframe>, and navigate it to some page on the chosen https://example.com domain (It doesn't matter what page, as long as you can insert a very little snippet of JavaScript on there. If you're creating the site, just make an empty page specifically for this purpose. If you're writing an extension or a Greasemonkey-style userscript and so don't have any control over pages on the example.com server, just pick the most lightweight page you can find and insert your script into it. Some kind of "not found" page would probably be fine).
(4) The script on the hidden iframe page need only (a) set document.domain = "example.com";, and (b) notify the parent window when this is done. After that, the parent window can access the iframe window and all its objects without restriction! So the minimal iframe page is something like:
<!doctype html>
<html>
<head>
<script>
document.domain = "example.com";
window.parent.iframeReady(); // function defined & called on parent window
</script>
</head>
<body></body>
</html>
If writing a userscript, you might not want to add externally-accessible functions such as iframeReady() to your unsafeWindow, so instead a better way to notify the main window userscript might be to use a custom event:
window.parent.dispatchEvent(new CustomEvent("iframeReady"));
Which you'd detect by adding a listener for the custom "iframeReady" event to your main page's window.
(NOTE: You need to set document.domain = example.com even if the iframe's domain is already example.com: Assigning a value to document.domain implicitly sets the origin's port to null, and both ports must match for the iframe and its parent to be considered same-origin. See the note here: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Changing_origin)
(5) Once the hidden iframe has informed its parent window that it's ready, script in the parent window can just use iframe.contentWindow.localStorage, iframe.contentWindow.indexedDB, iframe.contentWindow.BroadcastChannel, iframe.contentWindow.SharedWorker instead of window.localStorage, window.indexedDB, etc. ...and all these objects will be scoped to the chosen https://example.com origin - so they'll have the this same shared origin for all of your pages!
The most awkward part of this technique is that you have to wait for the iframe to load before proceeding. So you can't just blithely start using localStorage in your DOMContentLoaded handler, for example. Also you might want to add some error handling to detect if the hidden iframe fails to load correctly.
Obviously, you should also make sure the hidden iframe is not removed or navigated during the lifetime of your page... OTOH I don't know what the result of that would be, but very likely bad things would happen.
And, a caveat: setting/changing document.domain can be blocked using the Feature-Policy header, in which case this technique will not be usable as described.
However, there is a significantly more-complicated generalization of this technique, that can't be blocked by Feature-Policy, and that also allows entirely unrelated domains to share data, communications, and shared workers (i.e. not just subdomains off a common superdomain). #jcubic already described it in their answer, namely:
The general idea is that, just as above, you create a hidden iframe to provide the correct origin for access; but instead of then just grabbing the iframe window's properties directly, you use script inside the iframe to do all of the work, and you communicate between the iframe and your main window only using postMessage() and addEventListener("message",...).
This works because postMessage() can be used even between different-origin Windows. But it's also significantly more complicated because you have to pass everything through some kind of messaging infrastructure that you create between the iframe and the main window, rather than just using the localStorage, IndexedDB, etc. APIs directly in your main window's code.

Redirecting from a page when not accessed via an iframe without using JavaScript?

I need to redirect users if they try and access certain pages directly, i.e. not via the iframe I've provided. This is to stop them accessing other users' areas.
All the solutions I've found (which work, btw) use JavaScript - the current working script I have is
if (top == self) {
var newURL = 'http://www.exampleurlhere.co.uk/'
window.setTimeout('GotoIndex()',0);
}
function GotoIndex() { top.location.href = newURL; }
However, this will of course only work if the user has JavaScript enabled, which kind of scuppers me. Is there a way to achieve this server-side? I'm using aspx.
Thanks, Oli.
You can't check it severside as IFrame requests (in general) are no different from any other HTTP request. You can however use a GET parameter to indicate this is an IFrame
<iframe src="mypage?iframe=yes"></iframe>
Obviously this solution will only work if you're in control of the code that contains the IFrame, otherwise there is no way to do it server-side.

Categories