using window.onload function - javascript

<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');

Related

Onload event does not trigger

I want to send some data via postMessage from a page to another one which have different domains. However, I cannot achieve that since the code inside $(yo.document).load never runs; I tried the commented version as well. Here is my code:
<a onclick="popupCenter('http://localhost:58810');" href="javascript:void(0);">CLICK</a>
<script>
function popupCenter(url) {
const yo = window.open(url);
$(yo.document).load(function() {
//yo.document.onload = function() {
console.log("yo loaded");
yo.postMessage("Hello mate", "*");
});
}
</script>
</body>
</html>
The new window opens normally, however the callback inside load is not called. Any ideas?

make HTML page's element accessible in another HTML page

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");

set a value in .html file from an external .js file

i have a main.js that handles Key pressed. and i have a index.html that i want to recieve some variables from main.js and make decisions about it. for example i want to send a url from main.js to index.html .. i try this code in my main.js but not worked.
document.getElementById("url").value = "http://example.com";
in my index.html i have:
<form name="Params">
<input id="url" type="hidden" value="">
</form>
i just want to set value of my url input object from main.js.
any help?
It is important when did you call value assignment. It must be after DOM loaded. To do this you can try one of the followings.
Easiest way is just place your main.js script tag after /body close tag. it should work.
Assign the value in a function in main.js and call that function onload event.
--main.js
function assignValue()
{
document.getElementById("url").value = "http://example.com";
}
--index.html
<body onload="assignValue()" >
Your code looks fine to me but perhaps the code that triggers it isn't being fired. You haven't included the other part of your code that triggers the setting of the URL.
I'm guessing the reason it hasn't worked is because you're not waiting for DOM to initialize and the Web Browser has finished parsing the HTML.
The simplest 'fix' for this problem would be to hook into the window.onload callback in your main.js file:
// Wait for the DOM to finish loading.
var previousOnload = window.onload;
window.onload = function () {
// Execute any other `onload` function which may have been bound previously.
if (typeof previousOnload === 'function') {
previousOnload();
}
document.getElementById("url").value = "http://example.com";
});
However, it is preferred to listen for the DOM Ready event instead; if you're using jQuery then you can simply write:
// Wait for the DOM to initialize first.
$(function () {
document.getElementById("url").value = "http://example.com";
});
If you don't want to depend on jQuery then you could have a look into the super-lightweight DOMReady.js

How to insert a javascript file into an iframe then call a function in the inserted javascript?

Edit: Just found out this is a chrome problem, the code works fine in firefox
I have an iframe on a webpage that shows a book formatted as html. I would like to insert some javascript within this iframe to make the book more dynamic (e.g. click on sentences, show animations etc). The iframe content is in the same domain as the parent page.
I can insert the javascript into the iframe but get an error calling a function in the inserted javascript. I've described the different bits of code below:
My parent page javascript is:
function iframeLoaded()
{
var iFrameID = document.getElementById('preview-iframe');
var jsLink = iFrameID.contentDocument.createElement("script");
jsLink.src="/tests/iframeAPI.js";
jsLink.type = 'text/javascript';
iFrameID.contentDocument.head.appendChild(jsLink);
iFrameID.contentWindow.initialiseApi()
}
and the html containing the iframe is:
<iframe id="preview-iframe" width="640" height="240" frameborder="0" src="./testpage.htm" onload="iframeLoaded()" scrolling="no"></iframe>
The contents of iframeAPI.js is:
window.initialiseApi = function() { alert("Hello world") }
Looking at the iFrame's html in the browser shows that the iFrameAPI.js tag is inserted ok into the iframe head, but I don't get the alert popup when the page is loaded. The error appears on the following line:
iFrameID.contentWindow.initialiseApi()
Uncaught TypeError: Object [object Window] has no method 'initialiseApi'
However I can run this line in the browser's javascript console and the alert popup works fine.
Any help would be much appreciated.
Thanks,
Brian
Edit: I've just tried with an onload event to make sure the page is loaded and I still have the problem:
My parent page javascript is now :
function iframeLoaded()
{
var iFrameID = document.getElementById('preview-iframe');
var jsLink = iFrameID.contentDocument.createElement("script");
jsLink.src="/tests/iframeAPI.js";
jsLink.type = 'text/javascript';
iFrameID.contentDocument.head.appendChild(jsLink);
jsLink.onLoad= iFrameLoaded();
}
function iFrameLoaded()
{
alert("Iframe loaded"); // Alert works ok
var iFrameID = document.getElementById('preview-iframe');
iFrameID.contentWindow.initialiseApi(); // Same error message on this line
}
It sounds like you are trying to use the function before the content has loaded.
try this instead:
var t = setTimeout(iFrameID.contentWindow.initialiseApi(),500);
This will wait half a second before trying the function which should give the page tiem to load. Delay times are given in milliseconds.
An even better approach is to try using Jquery and its ready() method but this requires the jquery library to be loaded as well. Its well worth it though in my opinion, see http://api.jquery.com/ready/.
You would try something like:
$("body",iFrameID.contentWindow.document).ready(iFrameID.contentWindow.initialiseApi())
You're executing it right away without giving the script a chance to load. Hook up an onload event to your script block and run your main function then.
Try, in the page included in the iFrame, accessing the main page by doing something like:
window.parent.xyz = something;
Where something is what you want exposed to the main page. Could be a function or an object of functions. Now in the main page you can just do:
something(); // or something.somefunction();
You could also send window references, I think, but I have not tried that.
The easiest way is to call the initialiseApi function in the iframeAPI.js itself as it will be called as soon as it's loaded. The iframeAPI.js could look like that:
function initialiseApi() {
alert("Hello world");
}
initialiseApi();
There is no callback or timeout needed.

Javascript onload in HTML

I want to ask a question about the Javascript’s onload.
I’m writing a JSP page with the code <%# include file ="body.jsp". The included body.jsp contains:
<table onload="function()">
This should load the javascript function, but it doesn't appear to have any effect on the page. Is onload only usable on the body tag?
Onload can only be used for <body>, <img>, <script>, <iframe> tags, because it tells you when an external resource (image, script, frame) or the whole page (body) has been loaded
Since HTML5 these can also fire a load event: <link>, <style>, <input type=image>, <object>
Support for these can still be a hit or miss though (e.g. older Android browsers)
Why not just include it via a <script tag>?
Inside your .jsp file
<script>
window.onload = function() {
alert("Hello!");
}
// or to execute some function
window.onload = myFunction; //notice no parenthesis
</script>
As the other guys already stated the onLoad event will not fire on a table. What you can do ist attaching the onLoad-handler to the body element (which will then fire, when the page is loaded) and manipulate the table by for example assigning an id to the table.
<body onload="function() { var table = document.getElementById("table-id"); ... }">
<table id="table-id"></table>
</body>
Are you using some javascript framework?
"onLoad" may be used on body- and frameset-tags.
To see some action you may use:
<body onload="function(){alert('This is an action!')}">
The easiest way i find is to use an external javascript file and jquery.
// Variables and functions you want to declare
var socket = io.connect();
// .....
// Function you want to run on load
$(function() {
$('#submit').click(function() {addUser();});
// ... any other functions you want to run on load
});
This is a code snippet from something that i was working on. The variable is declared before the code runs (It creates a web socket).
Then there is the jquery document selector ($) which runs on load and calls the init function to modify my html. I use it to call an anonymous function which runs right away.
You can throw a <script> tag right after your table with code. Once it gets to the script tag it would mean that the DOM for the table element above it has been loaded and can now be accessed in your script below it.
Note: The following below isn't applicable to the question but rather the other answers being given.
I recommend using the addEventListener function in javascript for adding the event. This makes sure that you are not overwriting or going to be overwritten by anyone else wanting to listen to the event.
Example
var iframe = document.getElementsByTagName('iframe')[0];
iframe.addEventListener('load', function(event){ console.log("iframe Loaded", event); })

Categories

Resources