Call main page function from iFrame? - javascript

Yes, I have seen this question, but I am still finding myself confused:
How to Call JavaScript From Main Window
I want to call a function that toggles an object with jQuery on the parent frame from an iframe. How exactly would something be done?
window.parent.[...?]

In main window:
function toggleMe() {
$('#myid').toggle();
}
In child frame:
window.parent.toggleMe();

Related

iframe unable to call javascript function but can call parent javascript function

I am populating an iframe with the following content
<iframe sandbox="allow-same-origin allow-scripts" srcdoc="<!DOCTYPE html><html><head></head><body><div class="frame-root"></div></body></html>">
<html><head></head><body><div class="frame-root"><div class="frame-content"><div>
<script>
function parentGreet() {
console.log("parent greet")
window.parent.window['go']['main']['App']['Greet']("some name to greet").then(result => {
console.log(result)
})
}
</script>
<button onclick="parent.testingFromIframe('some data');">Call Parent Window Function</button>
</div></div></div></body></html>
</iframe>
In the parent index.html, I have
<script>
function testingFromIframe(greetee) {
window.parent.window['go']['main']['App']['Greet'](greetee).then(result => {
console.log(result)
})
}
</script>
so when I call this function testingFromIframe from the button onclick it works and the console.log(appears correctly).
However when i call parentGreet which is a function inside the iframe it does not work and says that the variable parentGreet doesn't exist.
One clue I can see is when I select the parentGreet function in the inspector it says that its a text node, which i feel suggests its not seeing it as javascript.
I have a bunch of functions attached to the parent window that I want to expose to the iframe. The only issue with the button onclick approach is receiving a response within the iframe and doing something with it.
I am in control of the content in the iframe, so if any one can point me in the direction of the best way to do this I would be very grateful - for instance, perhaps when the parent populates the content of the iframe, it could pass functions in to the iframe that became available to the iframe content or something.
Thanks

How to run script in parent window for child window?

My child.html have a button which could click using script $('[value="Submit"]').click();
I want to invoke this from parent.html
Something like this:
var popUp = window.open('https://child.html');
popUp.$('[value="Submit"]').click(); //this line should be fixed
How could do this?
You should use window.postMessage API. Here is example code.
child.html
function functionToBeExecuted(event)
{
// do click or whatever you want
}
window.addEventListener("message", functionToBeExecuted, false);
parent.html
let child = window.open('child.html');
child.postMessage(); // notice that I did not pass message argument, since you just want to trigger the function, but if you want to pass some data to function using event parameter, just pass data to this function (for example string or object etc.)
I went in a similar kind of issue where I had iframe(containing child html) inside my parent html.
I solved this $(".DivClass iframe").contents().find("button").trigger('click');
In your case its pop window I don't no which popup you are using: custom pop or browser pop.
You can Add iframe inside your popup to achieve this issue using the same code as what I did.
Condition is that popup should be custom html popup not the other popup which is provided by browser provide.
Use this code in parent.html to click button:
let child = window.open('child.html');
let doClick = () => child.document.getElementById('my-button').click();
child.addEventListener('load', doClick(), true);
This is what you want... But my suggestion is to make function on child and use window.postMessage API to trigger it...

Is there a way to load a function from the htm that you're loading with .load()? JQuery

In my main window main.htm I have a div button that loads another htm file into a large div when clicked. I use .load() to achieve this:
$('#mainpanel').load("search.htm");
There is a function in "search.htm" called test() which only consists of alert("hi"); and I want this to load when search.htm is loaded into the div. I used the body onload tag and window.onload = test; and even $( document ).ready() but nothing works. It only works if I access search.htm on its own, but if I access it through main.htm it does't alert "hi". Is there a way to use .load() to load the page and a function? or is there a way to get the function the onload when I select the div that loads the page?
The onload / document ready will only fire once (when the parent document is loaded)
Either add a
<script type="text/javascript">
test();
</script>
to the end of the search.htm (so it's executed after everything else in the page has been parsed) or call test(); from the parent page after the load completes (via a callback)...
$('#mainpanel').load("search.htm", function(){
test();
});
It depends which page you want to be responsible for executing the function. In the latter case, the parent page needs to know the name of the function in search which may or may not fit your design.
Using window.onload or $( document ).ready() doesn't make sense because the document is most likely already loaded when you run that function.
You can pass a callback to .load and access the function inside there. The callback is executed when the other page is loaded:
$('#mainpanel').load("search.htm", function() {
test();
});
Of course test must be in global scope for this to work.
As always, it's advisable to the read the documentation of the methods you are using: https://api.jquery.com/load/.

iframe with link, opens up colorbox in parent

So I have a small iframe with a bar graph, and I would like so that when I click the graph, it opens up a colorbox (with a more detailed graph) from the "PARENT" of that iframe...
Basically I can get the iframe to open a colorbox, but it's tiny, I need it to be as big as the parent window.
How do I achieve this? Full code please... I am new to this. Here is how far I am through now:
Parent code:
$(document).ready(function(){
function call_colorBox(params) {
$.colorbox(params);
}
})
iframe code:
<a onclick="parent.call_colorBox({ width: '80%', height: '80%', iframe: true, href:'dash6detail2.0xpay.php' });" href="#"><div id="chartContainer" style="max-width:440px;height: 250px;"></div></a>
But nothing seems to happen? What am I missing?
This question covers how this could be done:
Calling a parent window function from an iframe
And is well answered. They even cover the concept that you need both parent window and the iframe to be in the same domain. Should solve your conceptual problem.
Without your actual code examples it'd be hard to expand on with code but basically:
Header of parent window defines func "openColorBox"
Iframe sets click event on bar graph which when clicked calls parent.openColorBox
EDIT after code change in post:
Assigning the function inside the document ready closure made it inaccessible to the outer scope. So either remove it from the closure as commented below, or remove the document ready closure entirely.
So the code I originally had was correct, however needed to be taken out of:
$(document).ready(function(){
Thanks Nick for your help

Problems using window.opener

I have a simple ajax application
From this, a popup is launched, with a form.
Both the form resultpage, and the ajax application hava a javascript file in common.
From the popup window, in the form resultpage, I am trying to call a method from the common javascript file, to apply to the parent window.
My javascript file contains an updateLayer method, which when caleld from the parent window, works fine. I get nothing when trying to call it from the popup window.
The resultpage in the popup window has
<script type="text/javascript" src="x.js">window.opener.updateLayer("Layer3", "380118179930"); </script>
before any html.
Nothing happens in the parentwindow. I have also tried window.parent.
What is the reason and solution for/to this?
I assume this is related to this question, asked by another user that also happens to be named Josh.
In my answer to that question, I tried to explain that the functions from a Javascript file included in your parent window would be attached to the window object, so you use window.opener to get access to that window object to call them.
It looks like you've almost got this solved, but the problem here is that by including src="x.js" in the script tag from your form response, you're effectively overwriting any code placed inside the script. Plus, since x.js is included in the parent window, there's no need to have it in the popup at all, anyway.
The code for your form response should look like this:
<script type="text/javascript">
window.opener.updateLayer("Layer3", "380118179930");
</script>
I've removed the src="x.js" attribute, which would otherwise prevent code between the <script></script> tags from being executed.
Your problem can be that you have two JavaScript files with the same content, while no namespaces are applied.
First, your parent includes the file.js where your updateLayer() is defined. Then the parent opens the child window, which also includes that file.js. If you do that, you have two threads running, where each of them may have it's own functions and objects without bothering the other. I assume that your function is global. This can cause problems, if no namespaces are used. Also it can happen that your big ajax library creates iframes and things like that, and you won't see anything from that because it happens under the hood.
So try: top.window.opener.updateLayer("Layer3", "380118179930");
If that doesn't help, try to open a blank window with no included file.js and call that function from the opener. If that works, wrap the contents of that file.js in a namespace like myNamespace = {....big file content inbetween....}, make two versions of that (or better dynamically include the content) and make sure you have two different namespace. JavaScript is most often not working the way you think it should.
Also, make very sure that the url for your opened window has exactly the same domain. It can cause security issues so that the browser disallows access from a child window to it's parent.
Josh,
Can you determine if the function is triggered at all, like annakata suggests? E.g. by putting an alert box on the first line of the function?
Otherwise: how is the function updateLayer defined in x.js?
If it's defined like this:
function updateLayer(layer, result) {
// ...
}
...then it should work fine.
If it's defined as follows:
var updateLayer = function(layer, result) {
// ...
}
then it will not be available as property of the window object (and thus not available as property of window.opener either). In Firefox, at least; I haven't tested this in IE or other browsers.
Edit: why is this question tagged 'ajax'? AFAICS, all of the problem resides on the client side of the application; no ajax is involved.
Try following:
parent.window.updateLayer();
in a separate <script> tag.
I'm not quite sure whether it works with both src=some.js and inline script at the same time.
Since you have given the script element a src attribute, the results of x.js will be parsed as JS and the text content of the element will be ignored.
<script type="text/javascript" src="x.js"></script>
<script type="text/javascript">
window.opener.updateLayer("Layer3", "380118179930");
</script>
Create a new updateLayer function in you parent html file. Rename it different and call the original updateLayer from it.
e.g.
function updateLayerPage(arg1, arg2)
{
updateLayer(arg1, arg2);
}
and then call this new function from the child page
window.opener.updateLayerPage("Layer3", "380118179930");

Categories

Resources