will HTML <body> onLoad events overwrite javascript window onload event? - javascript

I have a HTML page and a javascript function is attached to the <body> onLoad event.
I wanted to show up a message dialog when the page loads. I cannot edit the javascript function attached to this onLoad event due to some reasons.
So I created a new javascript file with a single function which will show the message dialog. Then I added this line in my javascript file
window.onload = onPageLoad;
onPageLoad() is my function which could show the message dialog.
I attached this javascript file in my HTML using script tag. When I run this HTML file, onPageLoad() function is not getting called.
I want to know whether <body> tag, onLoad event overrides the window onload. If so, can someone help me in implementing this functionality somehow.
Please keep in mind that I could not edit my HTML file and I could write only new javascript file. Thanks.

Depends on browser. window.onload currently overwrites body onload in Chrome, Firefox and Safari on OSX
You can ADD your function to the onload:
window.onload = function() {
alert('window.onload')
}
if (window.addEventListener) {
window.addEventListener('load', function() {
alert('addEventListener')
}, false);
} else if (window.attachEvent) { // IE < 9
window.attachEvent('onload', function() {
alert('attachEvent')
});
}
<body onload="alert('body onload')">
</body>
AND/OR Replace
var bodyOnload = document.body.onload;
window.onload = function() {
alert('window.onload')
bodyOnload()
}
if (window.addEventListener) {
window.addEventListener('load', function() {
alert('addEventListener')
}, false);
} else if (window.attachEvent) { // IE < 9
window.attachEvent('onload', function() {
alert('attachEvent')
});
}
<body onload="alert('body onload')">
</body>

Related

window.onload Not Triggering in Injected Javascript?

I have a chrome extension that injects javascript code into a webpage like so
if (document.readyState === "complete") {
const html = `
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript">
console.log(location.href);
function doStuff() {
console.log("do stuff");
}
console.log("onload");
window.onload = function () {
console.log("WINDOW LOADED");
doStuff();
}
</script>
</body>
</html>
`;
document.write(html);
}
However, after I navigate to the page and the extension injects the javascript, I can see in the console that it does log location.href and onload, but the window.onload does not trigger, and I do not see WINDOW LOADED in the console, nor is doStuff() called.
I have also tried using
window.addEventListener('load', (event) => {
console.log('page is fully loaded');
});
as well as
document.addEventListener('DOMContentLoaded', doStuff);
to no avail.
Any help would be appreciated, I have not been able to find anything that works.
I managed to fix this by including at the top of my <script>
setTimeout(() => {
let evt = document.createEvent('Event');
evt.initEvent('load', false, false);
window.dispatchEvent(evt);
}, 300);
And this now causes window.onload to trigger. hope this helps anyone with the same issue

Chrome Extension - Trigger not Work

i try create simple Chrome Extension, after click button in pop-up, i need send function setInput() to page, function change value and i need use trigger('keyup'), if i try use this function in Chrome Console - trigger work. But if i send this function after click in pop-up - trigger not work(
Chrome Extension - Trigger not Work
Console - Trigger Work
popup.html
<head>
<script src="popup.js"></script>
</head>
<body>
<div class="btn">Click</div>
</body>
popup.js
function sendMessage() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
});
}
function onWindowLoad() {
chrome.tabs.executeScript(null, { file: "PageReader.js" });
}
document.addEventListener("DOMContentLoaded", function() {
var btn = document.querySelector('.btn');
btn.addEventListener('click', function() {
sendMessage();
});
});
window.onload = onWindowLoad;
PageReader.js
- in file top i include Jquery
function setInput() {
var input = $('.text input');
input.val('1111').trigger('keyup');
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
setInput();
}
}
);
thanks all for help, i find answer, i delete jQuery, and create event "keyup"
Old:
var input = $('.text input');
input.val('1111').trigger('keyup');
New:
var evt = document.createEvent('KeyboardEvent');
evt.initEvent('keyup', true, true);
var input = document.querySelector('.text input');
input.value = '1111';
input.dispatchEvent(evt);
Please add debugger after btn.addEventListener('click', function() { too see what is going on. if this event handler is attached.
Second thing - you may want to wrap you initialisation code into setTimeout call with let's say 100ms of delay, to check if this page you are dealing with is not only working with some framework that generates this HTML and this is done after DOMContentLoaded. This means basically wrap everything inside
document.addEventListener("DOMContentLoaded", function() {
with setTimeout(function() {/*everything inside goes here*/}, 100)

IE 11 onload is never called

My web page has following javascript
function LoadPDF(filename)
{
var loc = filename;
document.getElementById("pdf").setAttribute("src", loc);
if (window.addEventListener) {
document.getElementById("pdf").addEventListener("load", LoadPrint, false);
}
else if (window.attachEvent) {
document.getElementById("pdf").attachEvent("onload", LoadPrint);
}
else {
document.getElementById("pdf").onload = LoadPrint;
}
}
function LoadPrint() {
alert('fired!');
if (document.getElementById("pdf").src !== "") {
var frm = document.getElementById("pdf");
frm.contentDocument.getElementById("pdf").contentWindow.print();
}
}
The LoadPDF is called from code behind. "pdf" is my iframe. When the pdf is loaded into the iframe I want to call LoadPrint. But the trouble is in IE 11 its never called.
Can anyone please help?
This is an IE11 bug, which MS refuses to fix because they consider it a feature bug and they no longer fix that kind of bugs for old browser versions.
A workaround to this bug, is to load the pdf file inside an other page iframe and then load that page inside your iframe. A simple javascript pdf loader with a file argument:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PDF Loader</title>
<style type="text/css">
html, body {
border:0;
margin:0;
height:100%;
overflow-y:hidden;
}
#pdf {
border:0;
margin:0;
width:100%;
height:100%;
}
</style>
</head>
<body>
<iframe id="pdf"></iframe>
<script type="text/javascript">
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var pdf = getParameterByName('pdf');
document.getElementById('pdf').setAttribute('src', pdf);
</script>
</body>
</html>
You can use it with the <filename.html>?pdf=<pdf_file_to_load>.
Then you just change your code to load the pdf file through that loader like this:
function LoadPDF(filename)
{
var loc = "pdf-loader.html?pdf="+filename;
document.getElementById("pdf").setAttribute("src", loc);
if (window.addEventListener) {
document.getElementById("pdf").addEventListener("load", LoadPrint, false);
}
else if (window.attachEvent) {
document.getElementById("pdf").attachEvent("onload", LoadPrint);
}
else {
document.getElementById("pdf").onload = LoadPrint;
}
}
function LoadPrint() {
alert('fired!');
}
LoadPDF('http://www.pdf995.com/samples/pdf.pdf');
Now the LoadPrint function is called on iframe load event even on IE11.
Here is my working example you can even test with IE11: http://zikro.gr/dbg/html/ie11-iframe-pdf/
Here you can see a screen capture with the 10MB PDF loading and only after it finish loading it fires the load event and alerts the message:
I don't know if this is your specific issue in this instance, but make sure you bind your listeners to the element before you assign it's src attribute. If the item is in cache it is possible for the load event to fire before you bind to it, thus missing it entirely.

External JavaScript with jQuery dependence being loaded before jQuery

Externally loading a script, but my script was placed by the client above jQuery (which is a requirement), as such, my script does not work.
I am trying to make my code wait until jQuery has loaded before executing, but I am having difficulty with nested functions within my code; specifically $(x).hover, or $(x).click etc.
I can separate my functions without much trouble, which include jQuery selectors (but they won't be called unless 'x y or z' is done (i.e. until after jQuery is loaded).
I don't know how to have the hover, click etc implemented as they don't work within my $(document).ready(function(){... which is located within the onload yourFunctionName described below - with thanks to user #chaos
Link to onload hook: https://stackoverflow.com/a/807997/1173155
and a quote of the above link:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
yourFunctionName();
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Thanks in advance for any help with this.
I have also looked into a loop that checks if jQuery is activated before continueing, but did not implement it as I found that JavaScript does not have a sufficient sleep method that sleeps that specific script.
Solution:
if(typeof jQuery === "undefined"){
if(window.attachEvent) {
window.attachEvent('onload', myLoadFunction);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
myLoadFunction();
};
window.onload = newonload;
} else {
window.onload = myLoadFunction;
}
}
}
else {
myLoadFunction();
}

How can I check if the DOM is ready without a listener?

If I have a script that is loaded dynamically, I want it to wait until the DOM is ready before executing code. However, if the script loads too slowly, the DOM will already be ready and therefore the DOM-Ready function will not run.
No frameworks, please, I'm relying on pure JavaScript.
Thanks in advance!
Without a listener there's no 100% reliable way to ensure that the entire DOM is loaded. You can do something like this:
var myChecker = setInterval(function () {
var checkElem = document.getElementById('myRefElement');
if (checkElem != null) {
clearInterval(myChecker);
myFunction();
}
}, 100);
That'll wait until some target element you care about exists.
Part way down on this page: http://dean.edwards.name/weblog/2006/06/again/ you will find this code, which is what I use to do what you are asking about:
I leave the comment with the code as I didn't write it:
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
Very simple - put your script immediately before the closing body tag (if you have one). It doesn't guarantee that the DOM is ready, but it's more reliable that DOM ready listeners and runs earlier than load listeners.
Here are a couple of pure javascript domready events:
http://snipplr.com/view/6029/domreadyjs/
http://www.geekdaily.net/2007/07/27/javascript-windowonload-is-bad-mkay/
snippet that checks the document.readyState
http://www.dustindiaz.com/smallest-domready-ever

Categories