How to pass a URL to an iFrame using URL variables and javascript?

I found a javascript that allows me to pass pages to an iFrame(s) using coded links. I would like to also be able to pass URLs to the iFrame(s) using URL variables. I think I was close but I have never been able to come up with a solution that works. Can anyone show code added to what I have below that will add the ability to output a page in the iFrame(s) by passing the URL using URL variables.

The goals are:

1.) If a URL variable exists with a URL defined then the iFrame would output the page. (All domains will be on the same server so permissions should not be an issue.)

2.) If a URL variable does exist it should not interfere with the output with URLs passed to the iFrame(s) by clicking one of the links.

Let me know if you have questions or need additional information.

Thanks!

The main script:

<script type="text/javascript">

/***********************************************
* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
* Visit DynamicDrive.com for hundreds of original DHTML scripts
* This notice must stay intact for legal use
***********************************************/

//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
var iframeids=["myframe"]

//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
var iframehide="yes"

var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeCaller() {
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++){
if (document.getElementById)
resizeIframe(iframeids[i])
//reveal iframe for lower end browsers? (see var above):
if ((document.all || document.getElementById) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i])
tempobj.style.display="block"
}
}
}

function resizeIframe(frameid){
var currentfr=document.getElementById(frameid)
if (currentfr && !window.opera){
currentfr.style.display="block"
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight;
else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
if (currentfr.addEventListener)
currentfr.addEventListener("load", readjustIframe, false)
else if (currentfr.attachEvent){
currentfr.detachEvent("onload", readjustIframe) // Bug fix line
currentfr.attachEvent("onload", readjustIframe)
}
}
}

function readjustIframe(loadevt) {
var crossevt=(window.event)? event : loadevt
var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
if (iframeroot)
resizeIframe(iframeroot.id);
}

function loadintoIframe(iframeid, url){
if (document.getElementById)
document.getElementById(iframeid).src=url
}

if (window.addEventListener)
window.addEventListener("load", resizeCaller, false)
else if (window.attachEvent)
window.attachEvent("onload", resizeCaller)
else
window.onload=resizeCaller

</script>


The iframe:
<iframe id="myframe" src="" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" style="overflow:visible; width:100%; display:none"></iframe>


Example link:
<a href="javascript:loadintoIframe('myframe', 'myPage.htm')">Link</a>
CalDevAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

remorinaCommented:
Hi CalDev,
I'm not sure if I understand your request correctly.
I seems you're trying to pass predefined JavaScript URLs into the function of the iframe load

If so, you'll need to write an additional function to define your list of URLs into an array, then call the loadintoIframe function with passing the array value.

I've made an example code for you below, let me know if this is what you're after

Cheers
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>jQuery UI - Datepicker</title>
	<script type="text/javascript">

/***********************************************
* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
* Visit DynamicDrive.com for hundreds of original DHTML scripts
* This notice must stay intact for legal use
***********************************************/

//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
var iframeids=["myframe"]

//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
var iframehide="yes"

var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeCaller() {
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++){
if (document.getElementById)
resizeIframe(iframeids[i])
//reveal iframe for lower end browsers? (see var above):
if ((document.all || document.getElementById) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i])
tempobj.style.display="block"
}
}
}

function resizeIframe(frameid){
var currentfr=document.getElementById(frameid)
if (currentfr && !window.opera){
currentfr.style.display="block"
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight;
else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
if (currentfr.addEventListener)
currentfr.addEventListener("load", readjustIframe, false)
else if (currentfr.attachEvent){
currentfr.detachEvent("onload", readjustIframe) // Bug fix line
currentfr.attachEvent("onload", readjustIframe)
}
}
}

function readjustIframe(loadevt) {
var crossevt=(window.event)? event : loadevt
var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
if (iframeroot)
resizeIframe(iframeroot.id);
}

function loadintoIframe(iframeid, url){
if (document.getElementById)
document.getElementById(iframeid).src=url
}

if (window.addEventListener)
window.addEventListener("load", resizeCaller, false)
else if (window.attachEvent)
window.attachEvent("onload", resizeCaller)
else
window.onload=resizeCaller


// Newely Added Function

function passURL (mframe, murl) {
    URLs =  
        [ 
         "http://www.google.com",  
         "http://www.yahoo.com",
         "http://www.msn.com"
        ] 
    if (murl <= URLs.length) {
        loadintoIframe(mframe, URLs[murl]);
    }
}


</script>
</head>

<body>
    <iframe id="myframe" src="" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" style="overflow:visible; width:100%; display:none"></iframe>
    
    <a href="javascript:passURL('myframe', 0)">Load Google.com</a>
    <br />
    <a href="javascript:passURL('myframe', 1)">Load Yahoo.com</a>
    <br />
    <a href="javascript:passURL('myframe', 2)">Load MSN.com</a>
    <br />
    <a href="javascript:passURL('myframe', 7)">Will do nothing because this is an invalid array value</a>
</body>
</html>

Open in new window

0
dwkdCommented:
are you trying to redirect the iframe if the URL variable is passed inside the iframe src ?
for example if the ANCHOR HREF LOOKS LIKE THIS <a href="javascript:loadintoIframe('myframe', 'myPage.htm?URL=http://www.google.com')">Link</a>
if so add this js (snippet) inside your iframe, somewhere at the top

the code in the snippet looks for a url variable called "URL" and if it exists, it redirects the iframe to http://www.google.com

hopefully that was what you were trying to achieve :))
function getUrlVars()
{
var vars = [], hash;
var hashes = self.location.href.slice(self.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}

var urlvars = getUrlVars();

if(urlvars['URL']) self.location.href = urlvars['URL'];

Open in new window

0
CalDevAuthor Commented:
Well I thought when I wrote the description of what I was trying to do that I was very clear in my intention. However when I read back my description this morning I see that I wasn't nearly specific enough. Sorry about that.

1. So here is more detail on what I would like the script to do. I would like to be able to pass pages to the iframe, or possibly iframes, targeting iframes by id using formatted links. This function was already built into the script and it works.

2. Here is the part that doesn't exist. I would also like to be able to address this page with attached URL variables that would also be read by the script. For instance if this was the URL of the page and it had a URL variable included it might look like this: "www.thisIsMyPage.html?myframe=otherpage.thisIsMyPage.html" the code would then be able the grab the value of the URL variable "myframe" (doesn't have to be "myframe") and it would display the page address stored in the URL variable within the iframe on the page. Does that make sense so far?

Here is the code I was working with to grab  the value from the URL variables (it worked by the way):
 
 <script>
// Read a page's GET URL variables and return them.
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
 var getQueryVariable = 'not found';
}
</script>

I was able to get it to return the value of the URL variable.

Test:

<script>
  alert( getQueryVariable("myframe") );
</script>

The part I'm having trouble with is connecting this script with the one that pulls in the addresses for the iframe via links. Some how I need to have this address passed to the iframe if it exists and I was never able to work out the correct syntax. Also this needs to be setup so that if a user clicks on one the iframe links on the page it will then pull the URL from the clicked link into the iframe,  over riding the URL variable value in the iframe, which shouldn't be a problem.

OK does all that make sense? Please let me know if there is anything I can expand upon further.
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

CalDevAuthor Commented:
dwkd

I tried to implement your suggestion about the using the provided snippet in your post within my iframe but I'm keep getting an object expected error.  You were on the right path regarding path about passing a URL variable containing a web page address. See my post above. Hopefully you will get a chance to take a look at this.
0
dwkdCommented:
ok hopefully i understood what needs to be done

u start with a blank hidden iframe and only if there is a URL variable in the main window then load it inside the iframe?


try this: (snippet)


test for link index.html?URL=http://www.google.com
what i does is, when you click execute it looks at the url and if it finds a variable called "URL" it shows the iframe and redirects its contents to the link provided inside the URL variable, in this case http://www.google.com
if no URL var then nothing happens
<html>
<head>
<script>
function getUrlVars()
{
var vars = [], hash;
var hashes = self.location.href.slice(self.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}

var urlvars = getUrlVars();

function setURL(objid){
	var obj = window.document.getElementById(objid);
	if(urlvars['URL']){
		obj.style.display = "block";  //show iframe
		obj.src = urlvars['URL'];   //redirect iframe content to URL variable
	}

}
</script>
</head>
<body>

<a href="javascript:setURL('myframe');"> execute </a><br>
<iframe id="myframe" src="" frameborder="1" width="500" height="500" style="display:none;"></iframe>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CalDevAuthor Commented:
dwkd

This is really close now. I integrated your latest code with the what I already had and both function work together on the same page and I'm even able to use both scripts on my existing page and can output both using the same iframe. The only issue remaining is that the URL variable will not be called from a link on the same page but rather will be from a link on another page that will call this page with an appended URL variable. So I need this page to read a URL variable if it exists (like you have done here) but do the check when the page loads.

In other words when a user clicks a link on "pageA.html" they are taken to "pageB.html" with a URL variable appended like this "pageB.html?URL=http://google.com" and then since there is a URL variable with a web address stored in the variable the iframe would just load  http://google.com. I guess what I need is an "onload" command or something like that so that code would test for the URL variable without having to click a link. Unfortunately I don't have access to the body tag on the page so I would have to run the "onload"  command, or similar, from some other element on the page? Any idea how this could accomplished? I'm not very versed in the use onload functions. Hope this is making sense.
0
dwkdCommented:
just move the setURL('myframe'); to the <body onLoad="setURL('myframe');"> of pageB
0
CalDevAuthor Commented:
Since I am publishing through a CMS in which I don't have access to the body tag I was hoping there was another way to do the "onload". I did try using the body tag but of course this actually makes two body tags in the code since the one I can't access already exists. It did work in FireFox but it did not work in IE.  It worked in IE when I tried the code in a stand alone page but not in the CMS. I guess this might be because of the duplicate body tags? Any ideas?
0
dwkdCommented:
yep, here:
document.observe("dom:loaded", function(){

setURL('myframe');

});

Open in new window

0
CalDevAuthor Commented:
I tried everything I could think of to implement the last bit of code you provided so that I wouldn't have to bug you again but no luck.

Here is the IE error message I got when I tried to include the snippet in the existing script: "Object doesn't support this property or method".

When I was using onload in the body tag FireFox was working but not IE now neither one works. I'm guessing that I'm not implementing the snippet in the method you intended.

Here is the code I have now:
<script> 
function getUrlVars() 
{ 
var vars = [], hash; 
var hashes = self.location.href.slice(self.location.href.indexOf('?') + 1).split('&'); 
for(var i = 0; i < hashes.length; i++) 
{ 
hash = hashes[i].split('='); 
vars.push(hash[0]); 
vars[hash[0]] = hash[1]; 
} 
return vars; 
} 
 
var urlvars = getUrlVars(); 
 
function setURL(objid){ 
        var obj = window.document.getElementById(objid); 
        if(urlvars['URL']){ 
                obj.style.display = "block";  //show iframe 
                obj.src = urlvars['URL'];   //redirect iframe content to URL variable 
        } 
 
} 

document.observe("dom:loaded", function(){ 
 
setURL('myframe'); 
 
});
</script> 


<script type="text/javascript">

/***********************************************
* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
* Visit DynamicDrive.com for hundreds of original DHTML scripts
* This notice must stay intact for legal use
***********************************************/

//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
var iframeids=["myframe"]

//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
var iframehide="yes"

var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeCaller() {
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++){
if (document.getElementById)
resizeIframe(iframeids[i])
//reveal iframe for lower end browsers? (see var above):
if ((document.all || document.getElementById) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i])
tempobj.style.display="block"
}
}
}

function resizeIframe(frameid){
var currentfr=document.getElementById(frameid)
if (currentfr && !window.opera){
currentfr.style.display="block"
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight; 
else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
if (currentfr.addEventListener)
currentfr.addEventListener("load", readjustIframe, false)
else if (currentfr.attachEvent){
currentfr.detachEvent("onload", readjustIframe) // Bug fix line
currentfr.attachEvent("onload", readjustIframe)
}
}
}

function readjustIframe(loadevt) {
var crossevt=(window.event)? event : loadevt
var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
if (iframeroot)
resizeIframe(iframeroot.id);
}

function loadintoIframe(iframeid, url){
if (document.getElementById)
document.getElementById(iframeid).src=url
}


if (window.addEventListener)
window.addEventListener("load", resizeCaller, false)
else if (window.attachEvent)
window.attachEvent("onload", resizeCaller)
else
window.onload=resizeCaller

</script>



<a href="javascript:loadintoIframe('myframe', 'http://www.mydomain.com/testpage1.html')">Link</a>

<br /><br />

<a href="javascript:loadintoIframe('myframe', 'http://www.mydomain.com/testpage2.html')">Link 2</a>

<div style="height:2000px;">
<iframe id="myframe" src="" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" style="overflow:visible; height:100%; width:100%; display:none; border:0px;"></iframe>

</div>

Open in new window

0
dwkdCommented:
oops my bad, document.observe is from the Prototype JS framework

just add the file to the top of your code and you should be fine:

<script type="text/javascript" src="prototype.js"></script>




attached is the prototype.js file
prototype.js
0
CalDevAuthor Commented:
Well I'm now unable to get results in either FF or IE. Here's what I tried.
//Following your instructions literally
<script type="text/javascript" src="prototype.js"></script> 

//Tried putting the last snippet within the new script tags
<script type="text/javascript" src="prototype.js">
document.observe("dom:loaded", function(){ 
 
setURL('myframe'); 
 
});
</script> 

//Tried putting it all together with the main URL function
<script type="text/javascript" src="prototype.js">
function getUrlVars() 
{ 
var vars = [], hash; 
var hashes = self.location.href.slice(self.location.href.indexOf('?') + 1).split('&'); 
for(var i = 0; i < hashes.length; i++) 
{ 
hash = hashes[i].split('='); 
vars.push(hash[0]); 
vars[hash[0]] = hash[1]; 
} 
return vars; 
} 
 
var urlvars = getUrlVars(); 
 
function setURL(objid){ 
        var obj = window.document.getElementById(objid); 
        if(urlvars['URL']){ 
                obj.style.display = "block";  //show iframe 
                obj.src = urlvars['URL'];   //redirect iframe content to URL variable 
        } 
 
} 

document.observe("dom:loaded", function(){ 
 
setURL('myframe'); 
 
});

</script> 

Open in new window

0
dwkdCommented:
<script type="text/javascript" src="prototype.js"></script>

that's all you  need but make sure that the prototype.js file i attached in that previous post, is in the same directory as the file that is calling it.
0
CalDevAuthor Commented:
I guess that explains why I'm having a problem getting this to work on the live site. Unfortunately I can't store files on the CMS server where I'm placing this code. The site I do have access to for file storage is a subdomain of the CMS site. So in other words the CMS site would be "www.mysite.com" and the site where I can place the JS file is "web.mysite.com". Is this what's causing this not to work? When I run the exact same code on "web.mysite.com" it works for both IE and FF. Or could there be some kind of interference with the jQuery libraries that are part of the CMS site? I even tried including the entire contents of the prototype.js file in with the rest of the code but that didn't work either. If only there was a simple way to implement the "onload" command other than using the body tag.
0
dwkdCommented:
what you can do then is open this prototype.js file CTRL+A copy all the content and place it at the top of the page as showne below:

<script type="text/javascript">

PASTE CONTENT HERE

</script>

(you no longer need that line <script type="text/javascript" src="prototype.js"></script> )
0
CalDevAuthor Commented:
That's what I tried when I thought it causing a collision with the jQuery libraries built into the CMS. FireBug is reporting the following error:

element.dispatchEvent is not a function
[Break on this error] element.dispatchEvent(event);

From this function:

event.eventName = eventName;
 event.memo = memo || { };
 
 if (document.createEvent)
 element.dispatchEvent(event);
 else
 element.fireEvent(event.eventType, event);
 
 return Event.extend(event);
 }
0
CalDevAuthor Commented:
I did a little searching around on the internet looking for more information on the "onload" command and I found this:

Inline HTML: <ELEMENT onload = "handler" ... >  All platforms

Event property:    object.onload = handler JScript only

object.onload = GetRef("handler")   Visual Basic Scripting Edition (VBScript) 5.0 or later only

Named script <SCRIPT FOR = object EVENT = onload>  Internet Explorer only

Do you think the last one that shows IE only might work since the body onload already works for FF and this might take care of IE?
0
CalDevAuthor Commented:
OK I figured out a solution. I was able to pass the online code using an image tag on the page and both IE and FF have no problem loading the URL variable into the iframe.

Thanks for all your help.
0
CalDevAuthor Commented:
The reason I indicated partial on the completeness of the solution is that I had special, limiting circumstances on the server I was working with that effected the ability of the code to work. This was in no way a fault of the expert providing the solution and should not reflect on the quality of his work.
0
dwkdCommented:
no problem, glad to help

the prototype should be cross browser though
you can lose all the other functions that listen for a load event and add everything you want to be executed when the page is done loading inside the dom:load function

document.observe("dom:loaded", function(){
 
setURL('myframe');
 
//add more stuff here

});


anyways, good luck with your project
0
dwkdCommented:
Also the document.observe has to be the last bit of code, or at least after the functions it callas on dom:load
0
CalDevAuthor Commented:
Thank you for this follow up information. That actually cleared up a problem that I was having getting the URL variable to be recognized on the page (at least for IE not FF). I think the issue I'm having now is related to the fact that I added css/javascript drop down menus that are interfering with the jquery libraries already in the CMS. Do you know if there is a way to isolate my code in the page from interacting with the rest of the jquery libraries that are already loaded? I know it's a shot in the dark but thought I would ask.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.