window.onload Not Triggering in Injected Javascript? - 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

Related

javascript code onscroll in blazor not working

In a Blazor app I have a script.js file in wwwroot/js/script.js.
The javascript should call the scrollFunction while scrolling inside the app, but "Hello World" never comes up.
Why this javascript function is not called when I scroll up and down the page?
window.onscroll = function () { scrollFunction() };
function scrollFunction() {
window.alert("Hello World");
}
At the wwwroot/index.html I call this js file:
... <body>
<script src="js/script.js"></script> ...
at the _Imports.razor I added..
#using Microsoft.JSInterop
PS:
When I set in index.html
<head> ...<script>window.alert("Hello You");</script> ... </head>
or
<script>onmousedown = (event) => { window.alert("Click") };</script>
I get the Message.
But when I set
<script>window.onscroll = function () { window.alert("Hello World") };</script>
or
<script>onscroll = (event) => { window.alert("Scroll") };</script>
and scroll, I never get the message. The Problem is only with onscroll.

Nested Iframe doesn't have content after reload on Mozilla

I have this problem on Mozilla (worked perfectly on Chrome) where the nested Iframe doesnt have content after reload (only empty header and body tag)
Somehow you can click on the search bar and enter (instead of reload) to open again and all iFrame will load as intended
---------Working Snippet---------
https://codesandbox.io/s/determined-edison-9rwhwv?file=/index.html
Body index.html
<body>
<div>Index</div>
<iframe id="iframe"></iframe>
<script>
(function () {
var b = document.getElementById("iframe");
b.setAttribute("src", "iframe.html?" + Math.random() * 100);
})();
window.addEventListener('beforeunload', function (event) {
console.log('I am the 1st one.');
});
window.addEventListener('unload', function (event) {
alert('unLoad')
});
</script>
</body>
body iframe.html
<body>
<header>
IFRAME1
</header>
<iframe id="iframe2"></iframe>
<script>
(function () {
var b = document.getElementById("iframe2");
b.setAttribute("src", "iframe2.html?" + Math.random() * 100);
})();
window.addEventListener('beforeunload', function (event) {
console.log('frame 1 before unload.');
});
window.addEventListener('unload', function (event) {
console.log('frame 1 unload.');
});
window.addEventListener('pagehide', (event) => {
if (event.persisted === true) {
console.log('This page *might* be entering the bfcache.');
} else {
console.log('This page will unload normally and be discarded.');
}
});
</script>
</body>
Body iframe2.html
<body>
<header id="h2">
this is iframe 2
</header>
<script src="iframe2.js"></script>
</body>
I read something about bfcache, which is why i tried to put unload event to negate bfcache.
Found this thread with help from zer00ne about mixed content
Mixed Content warning on Chrome due to iframe src
But this seems to be a security issue to do
I got it working by calling the function after load event
window.addEventListener('load', function () {
function setIframe() {
var b = document.getElementById("iframe");
b.setAttribute("src", "iframe.html");
}
setIframe();
})
Hope this helps anyone.

Javascript not executing when right clicked into new tab

Here is my simple code
function goto() {
/* Some code to be executed */
if (a == "1")
location.href = "http://www.google.com";
else
location.href = "http://www.example.com";
}
And here is html
Hello
this works perfectly fine when i click normally but if i right click it and open in a new tab it doesn't execute.
try this:
Hello
function goto() {
/* Some code to be executed */
window.open("http://www.google.com");
}
if you want to open in new tab on mouse right click,
Hello
hit mouse right click and open in new tab
OR
u can try this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
function goto() {
window.location = "http://www.google.com";
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementsByTagName('a')[0].addEventListener('contextmenu', function (ev) {
ev.stopPropagation();
ev.preventDefault();
goto();
});
document.getElementsByTagName('a')[0].addEventListener('click', function (ev) {
goto();
});
}, false)
</script>
</head>
<body>
Hello
</body>
</html>
Try something like this:
Hello
<script>
document.getElementById('myId').addEventListener('contextmenu', function(ev){
gotoFunc(ev);
});
function gotoFunc(ev){
//run this when right clicked over #myId element
}
</script>
do it like this:
function changeDest(elem) {
/* Some code to be executed */
if (a == "1")
elem.href = "http://www.google.com";
else
elem.href = "http://www.example.com";
}
Hello
you can instead use Hello
This should do the trick. i.e adding the url to the href of the anchor tag

Why doesn't IE8 handle iframe onload events?

Sample code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function on_iframe_load() {
document.getElementById('iframe_a').onload = function() {
alert('Thanks for the visit!');
};
}
</script>
</head>
<body>
<iframe name="iframe_a" id="iframe_a"></iframe>
Go!
</body>
</html>
It works in all major browsers with no problem, but IE8 (and probably prior versions) don't understand it.
Update: Just came up with a solution, but I'm not sure if it's right coding. Please review:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
var clicked = false;
function activate() {
clicked = true;
}
function pop() {
if (clicked) {
alert('Thanks for the visit!');
};
}
</script>
</head>
<body>
<iframe name="iframe_a" onload="pop();"></iframe>
Go!
</body>
</html>
Using inline attribute on iframe seems to fix this issue in IE8:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function onIframeLoad(iframe) {
if(iframe.src) {
alert('Thanks for the visit!');
}
}
function onLinkClick(url) {
document.getElementById('iframe_a').src = url;
}
</script>
</head>
<body>
<iframe id="iframe_a" onload="onIframeLoad(this);"></iframe>
Go!
</body>
</html>
update by request:
You should try writing more unobtrusive javascript. Writing code in such way may prevent you from such strange bugs in IE.
<!DOCTYPE html>
<html>
<body>
<iframe id="display-frame"></iframe>
Go!
<script>
window.onload = function() {
var iframe = document.getElementById('display-frame'),
link = document.getElementsByTagName('a')[0];
// load handler
function onIframeLoad() {
alert('Thanks for the visit!');
}
// event handlers
if(iframe.addEventListener) iframe.addEventListener('load', onIframeLoad, false);
else if(iframe.attachEvent) iframe.attachEvent('onload', onIframeLoad);
link.onclick = function() {
iframe.src = this.href;
return false;
}
};
</script>
</body>
</html>
It seems you can't add a load listener to an iFrame in IE using the DOM property once the page has loaded.
But you can use attachEvent, so:
function on_iframe_load() {
function foo() {
alert('Thanks for the visit!');
};
var el = document.getElementById('iframe_a');
if (el.attachEvent) {
el.attachEvent('onload',foo);
} else if (el.addEventListener) {
el.addEventListener('load', 'foo', false);
}
}
I was testing in IE 6 and reversed the usual test order so that attachEvent is used in preference to addEventListener. You may want to test more recent versions of IE to see if the opposite order works and also test other IEā€“like browsers such as Opera.
Edit
Modified the code after testing (silly me) to use addEventListener. Here's something that works in IE and others:
function on_iframe_load() {
function foo() {
alert('Thanks for the visit!');
};
var el = document.getElementById('iframe_a');
if (el.attachEvent) {
el.attachEvent('onload',foo);
} else {
el.onload = foo;
}
}
And if you use an onload attribute in the markup, you don't need to add the listener using script.
It works :)
tested on IE8, ff, chrome
var iframe = document.getElementById('iframeid');
if (iframe .attachEvent) {
iframe .attachEvent('onload',alert("IE Iframe loaded"));
} else {
iframe .onload = alert("Other than IE Iframe loaded");
}
Just use jquery:
$(iframe).bind( 'load', function(){} );

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

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>

Categories