简体   繁体   中英

How can I run a JavaScript function based on an iframe's source?

Note: I see a few answers on running JavaScript when an iframe's source changes. I'm trying to run a JavaScript function on page load to change the header.

Basically, the following $(document).ready function has an if statement that doesn't seem to be reading the source correctly from my iframe.

Specifically, this "if(document.getElementById("obj").src == '/apex/MyDocumentsMobile')" statement doesn't do what I think it should be doing, asserting that the frames source is indeed '/apex/MyDcoumentsMobile'

$(document).ready(function() {
    if(document.getElementById("obj").src == '/apex/MyDocumentsMobile'){
        alert('wow'); //this doesn't work. I know my iframe has this src ,though.
        headerChanger('Documents');
    }
    $(".app-wrapper").delay(500).fadeIn(500); //this works, so my page fades in
});


//This function is called on other parts of the page and changes the header text just fine
function headerChanger(heady){
    head = heady;
    var element=document.getElementById("headText");
    element.innerHTML=heady;
}

        <iframe id="obj" src="/apex/MyDocumentsMobile" style="height:8000px;width:100%;position:relative;-webkit-overflow-scrolling: touch; " >
      </iframe>

One thing I would recommend trying to debug it is to alert the actual page source, like this:

alert(document.getElementById("obj").src)

I did this on this JSFIddle http://jsfiddle.net/U95RA/ and as you can see, even though the IFrame URL is set to a relative path, when you ask for the source, it returns the fully qualified URL (http://{domain}/path instead of just /path).

You can use a regular expression to check the URL ends with the path you expect:

if(document.getElementById("obj").src.match(new RegExp('/apex/MyDocumentsMobile' + "$"))){

Alternatively, and for better security (what if someone visits a URL that ends with that path but on a different domain), I would suggest changing your check to include the protocol and domain too:

if(document.getElementById("obj").src == 'http://whatever.com/apex/MyDocumentsMobile')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM