Javascript get element from opened window - javascript

I need to open a new window and return an element contained in it.
Say we have page A and page B, I want:
open B from A
get the element interested in B
return that element to A
I tried to do so in this manner, but it doesn't work:
var newwindow = window.open("http://www.example.com");
var elem = newwindow.document.getElementById('my-id').value;
Where am I wrong? Has anyone some advice to me?

Since you are using an absolute URI, I'm going to assume that you are trying to grab data from a different website. You'll therefore be blocked by the same origin policy.
If that isn't the case, then you're probably hitting a race condition by trying to read the content of the document before it has finished loading.
It would be a lot easier to help if you provided the error messages that your browser is almost certainly logging to its JS console.

If the new window has the same protocol, domain and port, your code should work. If it's on another domain, you can't do this for security reasons.
If you control both pages, you could use window.postMessage.

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.

window.parent.document.getElementsByTagName not working

var metaTags = window.parent.document.getElementsByTagName("meta");
console.log("hello"+metaTags.length);
My script is running in an iframe and I am not able to access the parent documents meta tags.The funning thing is nothing is getting printed on console.Not even Hellonull or something.
Thanks in advance
Swaraj
I am pretty sure you cannot execute cross frames/domains. If the domains match, you can do this, but if not, then it is a security issue that blocks it. Here is an example of doing so when the domains are the same: Getting parents document from iFrame

Update URL from inside an iFrame

is it possible for javascript inside an iFrame to update the URL (hash) of the parent page (and retrieve it)
Does it have any permissions?
To further explain, I have no hosting for this domain, I can only set up an Iframe. I also cannot use a DNS config to get that page to display because of limitations of my hoster.
I also cannot transfer the domain to them to make that work because my clients wants to keep control of the domain.
Thank you for your help!
If the <iframe> page is within the same domain, probably yes. Otherwise you don't get access to the parent page due to cross-domain restrictions.
You can change the URL of the parent page though:
top.location.href = 'http://www.example.com';
due to security constraints you will not be able to access properties of the parent window IF the domain,port or protocol is different than the one in the iframe.
To be short, the answer is NO.
Your script works only inside the context of that iframe.
If you try for example,
var loc = document.location;
you will see what I mean.
One solution is that when you give the other side your iframe, you should add a script in witch you can do whatever you want, because it runs on their domain.
Maybe dynamically create the source of your iframe and stuff.

Call the function only after the browser is fully redirected?

<script>
function test() {
alert("this should only be called after the browser is fully redirected?");
}
window.location = "http://google.com";
test();
</script>
I'm about redirecting the user guys to a page and I want to do something (call a function) only after the browser is fully redirected but I can't get it to work. Is there any way for me to do so?
Is there any way for me to do so?
Nope. When the page has opened google.com, you no longer have any control over the browser window.
Once URL changes, all execution of the current page is stopped.
Not really. You'd have to put the page you were redirecting in a frame and keep the script in another frame, then watch for the content frame to get updated. But you'd also run into cross-domain issues because of the Same Origin Policy (which governs access to one document's contents [the new page] from another document [the one containing the script you're running]). So basically, you can't do this.
If you post a separate question saying what you're trying to achieve by running more code afterward, it may be that people can help you with alternative approaches.
i don't believe this would work. it's a form of XSS/injection and therefore a security risk. i don't think the W3C allowed this sort of thing because it's very dangerous. as soon as the user is loading a different page, the browser ignores the previous one.
http://www.coderanch.com/t/439675/HTML-JavaScript/Javascript-call-AFTER-redirect
see that guy's answer for a visual

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