I have an HTML page say main.html which has an iframe (say id="myFrame")showing child.html page. Both of these pages have a button called "Hide frame". The onclick of these buttons calls hideFrame() JS function which is declared in main.js file. The hideFrame() function just change the display of myFrame to "none".
function hideFrame(){
document.getElementById("myFrame").style.display = "none";
}
The myFrame is in main.html file so the button in main.html when calls the hideFrame() function, it works. The frame gets hidden. But the same is not working if I call the function from child.html page.
How can I access this element (myFrame) form child.html page?
you should use the main.html's window object to assign the function to. So instead of
function hideFrame(){
document.getElementById("myFrame").style.display = "none";
}
you would do something like
window.hideFrame = function(){
document.getElementById("myFrame").style.display = "none";
}
Now the function is globally scoped on main.html's window.
The child frame has it's own window object. You need access to the parent window object to call the function from child.html.
From main.html, you can call hideFrame normally on click onclick = hideFrame(), but in child.html, you should put onclick = window.parent.hideFrame()
Instead of using an iFrame, I would use jquery to load in segments of html files from other files.
If that is not possible, you could inject Javascript code into the child frame that references objects in the parent. Ex:
child:
<script>
var x;
</script>
parent:
<script>
$("#myFrame").x = function(){
functionality / reference definitions
}
</script>
It took a while to understand what you are saying. From what I understand, you want to get access to an element on the top window from inside an iframe. Here is what to get access to the parent window:
var _parent = window.parent,
_parent_dom = _parent.document;
Then to get access to an element from the parent page (in this case #myFrame):
var my_frame = _parent_dom.getElementById("myFrame");
Related
I'm trying to call iframe2 function from iframe1
document.getElementById('cDiv').contentWindow.toggle_main();
var iframe = document.getElementsByTagName('iframe')[1];
iframe.contentWindow.myFunction();
The console is returning Uncaught TypeError: Cannot read property 'contentWindow' of undefined
I have also tried:
window.frames['iframe2'].toggle_main();
The function in iframe2 is called:
<script>
window.myFunction = function(args) {
alert("called");
}
</script>
The iframes are defined as:
<DIV id="cgDiv">
<IFRAME id="contentGenerator" SCROLLING="No" name ="iframe1" src="outlook.html">
</IFRAME>
</DIV>
<DIV id="cDiv">
<IFRAME id="content" SCROLLING="AUTO" verticalscrolling="yes" NAME = "iframe2" src="index.html">
</IFRAME>
</DIV>
Ideas on where the problem should be?
Javascript can't access functions in an IFrame directly. IFrames can access functions in their parent though.
So if your main page exposes a method RegisterCallback for instance, the IFrame can call it with one of its functions as parameter. The page can then store a reference to the function and call it at another time (with any parameters...)
UPDATE: Added example code
The code below is two files; index.html which is the master page with iframe(s), and child.html which is the page inside the iframe(s).
I've committed the example to github and you can test it by following this link. Due to browser security restrictions the code must be loaded from the same webserver and doesn't work if run directly from the filesystem.
I've intentionally included the child iframe twice to illustrate that any number of children can be registered with this technique. I leave it as an excercise to the reader to add a third iframe... :)
index.html
<html>
<body style="background:#efe">
<h1>This is the master page</h1>
<p><button id="setChildButton" type="button">Make child blue</button></p>
<iframe src="child.html"></iframe>
<iframe src="child.html"></iframe>
</body>
</html>
<script>
var childCallbacks = [];
function registerChild(callback){
console.log('Registering child callback');
childCallbacks.push(callback);
}
function onButtonClick(){
for (var i=0; i < childCallbacks.length; i++){
var callback = childCallbacks[i];
callback('blue');
}
}
window.onload = function(){
document
.getElementById('setChildButton')
.addEventListener('click', onButtonClick);
};
</script>
The javascript has a function registerChild() that it never calls itself, but can be called from child pages to register their endpoints.
When the button is clicked, all registered callbacks are called with the string "blue". It is then up to the childs endpoint to do something good with that. In this case changing its own background color.
child.html
<html>
<body id="childBody" style="background:#fee">
<h2>This is the child page</h2>
</body>
</html>
<script>
function setBackground(color){
var body = document.getElementById('childBody');
body.style.backgroundColor = color;
}
window.onload = function(){
if (parent && parent.registerChild){
console.log('registering with parent');
parent.registerChild(setBackground);
}
};
</script>
The javascript of the child checks if there is a parent (it is running inside an iframe) and that the parent provides a function called registerChild(). It then calls that function with a reference to its own function setBackground().
When the parent later calls the callback with the string "blue", it turns around and sets its own bodys background color to that value.
If all your documents share same origin, it should work, so calling
window.parent.frames['other frame name'].contentWindow['func']()
from within some frame will invoke func from neigbour iframe.
Behold hacky simplistic datauri example in Firefox (Chrome considers dataURI documents as always different origin, so it raises security exception)
data:text/html;charset=utf-8,<iframe id="a" src="data:text/html,<h1 id=a>0</h1><script>function inc(){a.innerHTML++}</script>"></iframe><iframe id="b" src="data:text/html,<button onclick=window.parent.frames.a.contentWindow['inc']()>inc in prevous frame</button>"></iframe>
// First iframe called (ifr_url) in Master page.
// Second iframe called (ifr_tab5) inside the master page.
// I want to call function (Hallow()) in second iframe.
var win = document.getElementById("ifr_url"); // reference to iframe's window
var doc = win.contentDocument? win.contentDocument : win.contentWindow.document;
var form = doc.getElementById('ifr_tab5').contentWindow.Hallow();
I am trying to assign value to javascript variable without refreshing page but its not working.
Consider example:
<head>
<script type="text/javascript">
var id='';
var source='';
function assignvalue(_id,_source){
//open div load in dialog box
id = _id;
source = _source;
}
</script>
</head>
<body>
<div id='load'></div>
<script>
_login.push(['login', 'callback_uri', 'http://localhost/Login/index/?source='+source+'&id='+id']);
</script>
</body>
In head define some variable globally and onclick of a tag I am opening div with load id and having global varible with new value.But new value is not assign to it below divs javascript.Any suggestion.
Thanks.
you are declaring two global variables id and source, but in your function definition you declare two local variables with the same name, so your desired changes to global variables are applied to local ones. Just rename the variables in the function definition.
For instance:
var id, source;
function assignvalue (_id, _source) {
id = _id;
source = _source;
}
Because the way you pass value cannot be
function assignvalue(id,source)
cause id and source in the function here will become local variable instead.
Please replace the variable in parsing to other name so that it work, i.e
function assignvalue(passID,passSource){
id = passID;
source = passSource;
console.log(id+" "+source);
}
then the global variable value will change.
You are declaring id and source twice: once in the global scope, and once as function parameters.
To overwrite the values of the global variables inside the function, you need to use a different name for the parameters.
Try
function assignvalue(_id, _source) {
id = _id;
source = _source;
}
To execute the _login function when the link is clicked, you could simply call it in assignValue:
function assignvalue(id, source) {
_login.push(['login', 'callback_uri', 'http://localhost/Login/index/?source='+source+'&id='+id']);
}
In that case, it wouldn't be a bad idea to rename the function assignvalue to login
Yes, whatever you have written is correct.
But when you click on an HyperLink it will automatically refreshes the page.
Here you want to disable that auto refresh when you click on the Hyper link.For that you could amend your code like this:
<html>
<head>
<script>
var id,source;
function assignValue(_id,_source){
id = _id;
source = _source;
alert(_id+" and also "+_source);
}
</script>
</head>
<body>
<script>
alert(id+" I am in Body "+source);
</script>
Hello
</body>
OR alternatively you can try this
<html>
<head>
<script>
var id,source;
function assignValue(_id,_source){
id = _id;
source = _source;
alert(_id+" and also "+_source);
return false;
}
</script>
</head>
<body>
<script>
alert(id+" I am in Body "+source);
</script>
Hello
</body>
Extra Info:
To override the default browser functionality, just you have to return false.
Not only here, almost you can apply this in many situations.
One such situation is disabling right click(simply) is just
oncontextmenu= return false;
and another such situation is disabling a KeyPress Event and so on.
So, you can apply this almost anywhere.
I have a textarea box where the user inputs HTML and it gets output into the body element of an iframe.
This works just fine using most HTML tags, but if you use the <script> tag (in order to add JavaScript), the script element does not get transferred to the iframe.
For example, I should be able type the following in the textarea:
<script>
function test() {
alert('test');
}
</script>
<button onclick="test()">test</button>
The button gets added to the iframe but since the script element apparently doesn't, clicking the button does not fire the alert().
One work-around for this is to declare alert() on the button click, rather than using a pre-scripted function; this work-around is shown below:
<button onclick="alert('test')">test</button>
However this only allows one javascript command (whereas the user may want to use a function with multiple commands).
You can see the webpage here
The JavaScript to fill the iframe contents is:
(function () {
$('.grid').height($(window).height());
var frame = $('iframe'),
contents = frame.contents(),
body = contents.find('body'),
styleTag = contents.find('head')
.append('<style></style>')
.children('style');
$('textarea').focus(function () {
var $this = $(this);
$this.keyup(function () {
if ($this.attr('id') === 'html') {
body.html($this.val());
} else {
styleTag.text($this.val());
}
});
});
})();
The problem is any "user-generated" scripts will be executed in the parent window's global context (which the iframe cannot [normally] access). The console shows the following error when clicking the button because the test() function is not accessible scope-wise for the iframe:
Uncaught ReferenceError: test is not defined
To fix this, scripts need to add functions to the global scope of the iframe's internal window:
<script>
(function () {
'use strict';
var iframe = document.getElementById('iframe'), //grab the iframe
win = iframe.contentWindow; //get the window of the iframe
win.test = function () { //declare function in scope of iframe's window
alert('test'); //now "test" will fire because it's defined in a scope accessible to the iframe
};
}());
</script>
<button onclick="test()">test</button>
I have one single iframe within parent page on the same domain. I need when ID 'applications' is found in iframe to trigger changes in parent page.
Is this javascript function correct ?
function load(){
if (window.frames[0].document.getElementById('applications'))
{
var str=document.getElementById("tst").innerHTML;
var n=str.replace("Login","Delogare");
document.getElementById("tst").innerHTML=n;
document.getElementById('tst').title ='logout';
document.getElementById('tst').href='logout';
document.getElementById('prt').href='../profil/cont.html?refresh';
}}
<script type="text/javascript">
function init() {
document.write("www.sabah.com.tr opened..")
}
function start() {
var myWin = window.open("http://www.sabah.com.tr","_blank");
myWin.onload = init; // i think the poroblem is here..
}
setTimeout(start, 5*1000);
</script>
i want to call init function when my new page loaded but there is a problem.. init function didnt call when page loaded.. so how can i call init function?
There are several problems with that code:
The function will be run in the scope of the current page, not the newly opened page.
You can't use document.write after the page has loaded, that will scrap the page and replace it with the string specified.
If the page is loaded from a different domain, you can't access it in any way.
unless the URL you are opening is the same domain, you do not have access to the newly created window object.
Try opening the window first with an empty URL, then performing the operation/attaching the handler, and then loading the content (mywin.location = ...).
Try trigger function
myWin.onload=$('#form_id').trigger('init');