Changing iframe src with jquery - javascript

I am trying to change my iframe src and reload the iframe with the following code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$('#changeframe').click(function () {
$('#declinedframe').attr('src', 'http://stackoverflow.com');
});
</script>
<input type="button" id="changeframe" value="Change">
<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>
When I click "Change" on the button nothing happens. What I am doing wrong?

The order does matter.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="changeframe" value="Change">
<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>
// Go Last since changeframe hasn't exist yet.
<script>
$('#changeframe').click(function () {
$('#declinedframe').attr('src', 'http://stackoverflow.com');
});
</script>

If the code is as it is in your example, you need to wrap the jQuery in
$(function() { ... }); or move it below the html since the button
does not exist when the script runs
Look in the console. You MAY not be allowed to change the src of an iframe containing a url from another domain - some browsers like IE can throw a security exception. You could have access denied in the console
Some websites do not allow their pages to be framed. It is not the case in your example but would for example give errors if you try to load google in a frame
$(function() {
$('#changeframe').click(function() {
$('#declinedframe').attr('src', 'http://stackoverflow.com');
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="changeframe" value="Change">
<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>
Using a link - no need for jQuery (same if the button above was submitting a form, target iframename):
Change
<iframe name="declinedframe" id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>
If you MUST use jQuery for the link give it the ID of changeframe use
$(function() {
$('#changeframe').on("click",function(e) {
e.preventDefault(); // cancel the link
$('#declinedframe').attr('src', this.href );
});
});

Related

Access-Control-Allow-Origin and document.domain not working

I have an iframe inside a PHP page and I am trying to access a parent element from within the iframe, but always get this error in the Console:
Uncaught DOMException: Blocked a frame with origin
https://subdomain.domain.com from accessing a cross-origin frame.
I have read every single search result on Google's first page around Same Origin policy and Access-Control-Allow-Origin but that doesn't seem to be solving my problem. I am still getting the same error.
Here is what I have done so far:
Added Access-Control-Allow-Origin into my iframe content.
Added document.domain into my iframe content.
Has anybody else had similar problem? What can I do to fix it?
Here is my code:
<?php
header('Access-Control-Allow-Origin: https://b.example.com');
?>
<script>
function receiveMessage(event) {
if (event.origin !== "https://a.example.com")
return;
}
window.addEventListener("message", receiveMessage, false);
</script>
<div>
<button title="Close (Esc)" type="button" class="close">×</button>
</div>
<iframe name="myIframe" class="myIframe"
src="https://b.example.com" width="100%" height="600px"
frameborder="0" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="">
</iframe>
</div>
Script in b.example.com
<script>
window.parent.$('.close').click(function () {
var thisObj = this;
if (!feedbackLoaded) {
$('#openFeedback').click();
feedbackLoaded = true;
$('#feedbackForm .close').click(function () {
window.parent.$.magnificPopup.proto.close.call(thisObj);
});
return false;
} else {
window.parent.$.magnificPopup.proto.close.call(thisObj);
}
});
</script>
Regardless to https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage you can implement communication between your document and iframe.
In this case you have to specify all operations that will be available on parent window. Here is an example:
Parent window:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<script>
function receiveMessage(event) {
console.log(event);
if (event.data.message === 'Hello world') {
$('#openFeedback').click();
}
}
window.addEventListener("message", receiveMessage, false);
</script>
<div>
<button title="Close (Esc)" type="button" class="close">×</button>
</div>
<iframe name="myIframe" class="myIframe"
src="http://b.test.dev" width="100%" height="600px"
frameborder="0" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="">
</iframe>
</body>
</html>
And subdomain in iframe:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<script>
window.parent.postMessage({message: 'Hello world'}, 'http://test.dev');
</script>
</body>
</html>
Also you should provide some security check for iframe identity like you added in your example. In that case you don't need to add cross-origin header

Understanding which div is clicked by the end user while opening a modal window

I would like to open a modal view when a user creates some hyperlinks. There will be many hyperlinks on the page, so I would like to understand which div, related to the clicked hyperlink, I should present the user as a modal view.
The code I wrote is:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Test</title>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
<script>
function OpenModal() {
$("#divModal").dialog({
autoOpen: false, modal: true, title: 'Modal', width: 'auto', height: 'auto'
, buttons: { "Cancel": function () { $(this).dialog("close"); } },
}).dialog('open');
return false;
}
</script>
</head>
<body>
View Page
<div style="display:none;" id="divModal" >
<iframe id="myIframe" src="/menu.php" width="1000" height="800" ></iframe>
</div><br />
<a href="#" onclick="javascript:OpenModal();" >Trip Planning</a>
<div style="display:none;" id="divModal2" >
<iframe id="myIframe2" src="tripplanning.php" width="1000" height="800"></iframe>
</div><br />
</body>
</html>
All I want is to make #divModal in the OpenModal function dynamic, the clicked div it should be.
I appreciate if someone helps. Thanks.
EDIT: What should I do if there is a specific <a> that should redirect user to another page instead of displaying a modal view? How can I check it in the js function?
Find a bus
<div style="display:none;" id="divRedirect1" >
<iframe id="myIframe3" src="/transit/findbus.php" width="800" height="600"></iframe>
</div>
For example, here if user clicks 'Find a bus', the user should go to the findbus.php, not see a modal view.
Thanks.
EDIT2: I have just notified that the selected correct answer of this question also advises me to use class while defining <a> tags. So I followed his advice. The problem has solved like:
Trip Planning
<div style="display:none;" id="divModal" >
<iframe id="myIframe1" src="/transit/access_a_bus.php" width="800" height="600"></iframe>
</div>
Find a bus
<script>
$(function() {
$('.displayModalView').click(function(e) {... //same what he wrote...}
});
</script>
Firstly, change the href attribute of the a element to be a selector for the div you want to turn in to a modal, and also remove the outdated onclick attributes.
View Page
<div style="display:none;" id="divModal" >
<iframe id="myIframe" src="/menu.php" width="1000" height="800" ></iframe>
</div><br />
Trip Planning
<div style="display:none;" id="divModal2" >
<iframe id="myIframe2" src="tripplanning.php" width="1000" height="800"></iframe>
</div><br />
You can then hook to the click event of those a elements in JavaScript:
<script>
$(function() {
$('a').click(function(e) {
e.preventDefault();
var target = $(this).attr('href');
$(target).dialog({
autoOpen: false,
modal: true,
title: 'Modal',
width: 'auto',
height: 'auto',
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
}).dialog('open');
});
});
</script>
I would suggest you make the a selector a little more specific by using a class, however this will work given the HTML in your question.

How to change iframe src

Please bear with me if i'm asking something very basic as I don't know much about coding. I have a stock charting application which has a built-in web browser. I configured this browser to load a html page, which i coded as below, like this mypage.html?symbol=xzy, What i am trying to do here is to capture the submitted html variable, 'symbol' and use its value as part of the url string to load a portion of another third party webpage. I can't figure out what's wrong with my javascript code that is failing to set the value of the 'src' attribute. Any help is most appreciated.
<html>
<header>
<script>
document.getElementById('iframe').src = "http://www.asx.com.au/asx/markets/dividends.do?by=asxCodes&asxCodes="+symbol+"&view=all#dividends";
</script>
</header>
<body>
<div id="dividends"></div>
<iframe id="iframe" src="" style="display:hidden;margin-left: -140px; margin-top: -33px" scrolling="no" frameborder="no" width="398" height="265"></iframe>
</body>
</html>
try move the script after html DOM
<body>
<div id="dividends"></div>
<iframe id="iframe" src="" style="display:hidden;margin-left: -140px; margin-top: -33px" scrolling="no" frameborder="no" width="398" height="265"></iframe>
</body>
<script>
document.getElementById('iframe').src = "http://www.asx.com.au/asx/markets/dividends.do?by=asxCodes&asxCodes="+symbol+"&view=all#dividends";
</script>
A couple of things: 1) start with performing the function onLoad - that way you know the script will run and popluate the src attribute after the browser renders it, and not before.
2) use a function to get the url value.
<html>
<header>
<script>
<!-- source: http://javascriptproductivity.blogspot.com/2013/02/get-url-variables-with-javascript.html -->
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] == VarSearch){
return KeyValuePair[1];
}
}
}
function SetContent(){
var symbol = GetUrlValue('symbol');
document.getElementById('iframe').src = "http://www.asx.com.au/asx/markets/dividends.do?by=asxCodes&asxCodes="+symbol+"&view=all#dividends";
}
</script>
</header>
<body onLoad="SetContent();">
<div id="dividends"></div>
<iframe id="iframe" src="" style="display:hidden;margin-left: -140px; margin-top: -33px" scrolling="no" frameborder="no" width="398" height="265"></iframe>
</body>
</html>
Move the javascript to the bottom of the page AFTER the iframe. You are trying to change an element before it is created. Also do src="about:blank" initially, so it validates.

Loading of an iframe after another

I have two iframes in my web page, and I want to load the second iframe after the first iframe has finished loading. How can I do this? I tried using the settimeout function, but I encountered some problems.
This is my code:
<iframe src="firstiframe" frameborder="0" widht="100%" marginheight="0" marginwidth="0" scrolling="NO" id="the_iframe">
</iframe>
<iframe src="secondframe" frameborder="0" widht="100%" marginheight="0" marginwidth="0" scrolling="NO" id="the_iframe2" >
</iframe>
<script>
function resizeIframe(iframeID)
{
document.setTimeout("resizeIframe",1000);
var iframe = window.parent.document.getElementById(iframeID);
var container = document.getElementById('content');
iframe.style.height = container.offsetHeight + 'px';
}
</script>
You can use the jQuery ready function on the frame to see when it's loaded and then set the src url for the second frame. Something like:
$('#firstframe').ready(function() {
$('#secondframe').attr('src', 'http://yourlink');
});
You can do something like this:
$("#firstIframe").load(function (){
$("#secondIframe").load();
});
I would do this with jquery:
First iframe:
<iframe id="iframe1"></iframe>
<div id="loadsecondIframeHere"></div>
<script>
$('#iframe1').ready(function(){
$('#loadsecondIframeHere').html('<iframe id="iframe2"></iframe');
});
</script>
or use $(document).ready()

How pass data to parent window from iframe?

I using 3 .asp pages
Page 1 :Parent.asp
page 2 :Subparent.asp
Page 3 :Child.asp
using javascript in the child.asp. I wand to pass data from Child window(iframe) to Parent window
<title>parent.asp</title>
<html>
<body>
<iframe name="I1" frameborder="0" scrolling="no" src="Subparent.asp" width="100"
height="100">
<title>subparent.asp</title>
<html>
<body>
<div id ="parentdata"></div>
<iframe name="I1" frameborder="0" scrolling="no" src="Subparent.asp" width="100" height="100">
<title>subparent.asp</title>
<html>
<body>
<iframe name="I1" frameborder="0" scrolling="no" src="Child.asp" width="100" height="100">
<title>subparent.asp</title>
<html>
<body>
<script language="JavaScript">
{
parent.document.getElementById("parentdata").innerHTML="GET DATA, WORKING"
}
</script>
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
In the "Child.asp" i using javascipt. i wand to pass data to the "" of "parent.asp"
is it possible, plz help me
hoping your support
maybe ajax is the best way to do what you need.
but if you still prefer the iframes, you can try:
Parent.asp:
function myFunction(pram1, param2)
{
alert('worked! - param1: '+param1.toString()+' param2: '+param2.toString());
}
Child.asp
top.myFunction(1,2);
for some old-school info on windows and frames: http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/window.html#1200703 which seems, as TeKapa reckons, to still work.

Categories

Resources