Alert when iframe url changed - javascript

This script runs every 2 seconds and detect if the url of the iframe is changed. But I can't get it to work. I want to alert if the url of the iframe is changed. For example if someone clicks a link and go another page on the iframed content.
var prevSrc = "http://www.bodrumlife.com";
function check() {
var curSrc = $('#iframe').attr('src');
if (curSrc != prevSrc) {
alert("hobaa");
prevSrc = curSrc;
}
}
window.setInterval(check, 2000); // 2 seconds
<iframe id="iframe" name="iframe" src="http://www.bodrumlife.com"></iframe>

If you prefer to use JQuery below is the following syntax, instead of using half-jquery and standard javascript.
$(function(){
$('#iframeId').load(function() {
alert("the iframe has changed.");
});
});
Although I'm not sure if the onload function works in Sarafi. It's supported by Firfox, IE and Chrome.
EDIT:
extended example
<script type="text/javascript">
$(function () {
var intialFrameSrc = "http://www.twiij.com";
$("#iframeContentPanel").load(function () {
if (intialFrameSrc != $("#iframeContentPanel").attr('src')) {
alert("the iframe has changed.");
}
});
$("#btnChangeUrl").click(function () {
$("#iframeContentPanel").attr("src", "http://m.smh.com.au/");
});
});
</script>
<iframe id="iframeContentPanel" name="iframeContentPanel" src="http://www.twiij.com" width="500" frameborder="0" height="500" scrolling="no"></iframe>
<input type="button" id="btnChangeUrl" value="Change Url"/>

Related

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 onblur / onfocus with iframe not working issues

I use onblur and onfocus function in my page.
But also, I use a iframe into page.
And my problem is onblur and andfocus functions not working together into page if I use a iframe.
I clicked in iframe when onblur function is working.But I dont want this function work if I clicked in iframe. I want to run only work it if user will change browser tab
if I will use hasFocus function and users changes browser tab , this time onblur is not working
my js codes:
var after_title = 'Back to page';
var dafault_title = document.title;
var deg;
window.onblur = function () { document.title = after_title; beep(); deg=setTimeout(check,2000); }
window.onfocus = ()=>(deg)?clearTimeout(deg):null;
function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYU=");
snd.play();
}
function check()
{
if(document.hasFocus()){
document.title = dafault_title;
return;
}else{
location.href = './index.php';
}
}
<html>
<head>
<title>Demo Page</title>
</head>
<body>
<br><br><br>default page<br><br><br>
<br><br><br><br>
<iframe id="abc" name="abc" frameborder="1" marginwidth="0" marginheight="0" framespacing="0" width="100px" height="100px">
<p>example include page</p>
</iframe>
</body>
</html>
In order to react to tabchange, don't use the blur and focus events, but rather the Page Visibility API instead:
function handleVisibilityChange() {
if (document.hidden) { // equivalent to "blur"
document.title = after_title; beep(); deg=setTimeout(check,2000);
} else { // equivalent to "focus"
if (deg) {
clearTimeout(deg);
}
}
}
document.addEventListener("visibilitychange", handleVisibilityChange, false);

How to disable iframe right click for every website

I have a problem about right click for the iframe. I've done it for the default url of the IFrame but when i displayed any other webpage right click can be usable. I have used those sample codes,
document.onmousedown = disableclick;
status = "Right Click Disabled";
function disableclick(event) {
if (event.button == 2) {
return false;
}
}
function disableContextMenu()
{
document.getElementById("myFrame").contentWindow.document.oncontextmenu = function () { return false; };
}
Here is the iframe
<iframe id="myFrame" name="myFrame" width="1603" height="1064" style="border:none;" src="Iframe.aspx" onload="disableContextMenu();" oncontextmenu="return false"></iframe>
I found the css code "pointer-events:none" but i makes the frame unclickable.
include jquery and then apply this
$( document ).ready(function() {
$('#myFrame').on('contextmenu', function(e) {
e.preventDefault();
});
});
thanks
hope this help

dynamically set iframe src

I have a program which will dynamically set an iframe src to load pages. I need to hook a event handler for the page completely loaded. How can i do it? Thanks!
<script type="text/javascript">
function iframeDidLoad() {
alert('Done');
}
function newSite() {
var sites = ['http://getprismatic.com',
'http://gizmodo.com/',
'http://lifehacker.com/']
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://getprismatic.com/" onLoad="iframeDidLoad();"></iframe>
Example at http://jsfiddle.net/MALuP/
Try this:
top.document.getElementById('AppFrame').setAttribute("src",fullPath);
Try this...
function urlChange(url) {
var site = url+'?toolbar=0&navpanes=0&scrollbar=0';
document.getElementById('iFrameName').src = site;
}
TEST
You should also consider that in some Opera versions onload is fired several times and add some hooks:
// fixing Opera 9.26, 10.00
if (doc.readyState && doc.readyState != 'complete') {
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
Code borrowed from Ajax Upload
try this code. then 'formId' div can set the image.
$('#formId').append('<iframe style="width: 100%;height: 500px" src="/document_path/name.jpg"' +
'title="description"> </iframe> ');
Try this:
document.frames["myiframe"].onload = function(){
alert("Hello World");
}

Can one set an iframe's src and manipulate its contents afterwards?

My goal is to have a parent page change the src of an iframe from blank to its proper url (as to utilize an onload handler in the iframe at a given point, but that's beside the point) and then manipulate the iframe's contents. However, javascript seems oblivious to any elements of an iframe that aren't on its src when the DOM loads. Is there any way around this?
The setTimeouts are intended to allow the DOM and iframe to load.
edit:fixed some stuff.
Here's the containing page:
<html><head>
<script type="text/javascript">
var done = false;
var theIframe;
window.onload = function () {
setTimeout('stuff()', 2000);
clearTimeout('stuff()');
}
function stuff() {
if (!done) {
theIframe = window.myiframe;
theIframe.src = 'http://localhost/TestStuff/redirectIframe.jsp';
done = true;
stuff();
} else {
theIframe.setMe = true;
}
}
</script>
</head>
<body>
<iframe src="" width="500" height="500" id="myiframe" name="myiframe">
</iframe>
</body>
And here's the iframe:
<html>
<head>
<script type="text/javascript">
var setMe = false;
window.onload = setInterval('checker()', 1000);
function checker() {
alert('hi');
if (setMe) {
window.onload = null;
top.location = 'http://www.google.com';
alert('foundit');
} else alert('a');
}
</script>
</head>
<body></body>
</html>
Any ideas?
In this piece of code:
theIframe.src = ...;
stuff();
you're calling stuff() immediately, contrary to what you have described, so in fact you're not allowing any time for the page to load. Maybe you're confused about how setTimeout works: it just schedules a single execution after the specified time, it doesn't automatically delay all calls to a function.
Also, you can use clearTimeout only with a previous ID returned by setTimeout, not with code as you have now.
Try something like this:
window.onload = function() {
loadFrame();
}
function loadFrame() {
theIframe = ...;
theIframe.src = ...;
setTimeout(setSomething, 2000);
}
function setSomething() {
theIframe.setMe = true;
}

Categories