简体   繁体   中英

How to check whether anchor tags within an iframe contain a URL

I'm working on a page which is dynamically generated via a CGI system, where the site's real developer doesn't have the time to make changes to the python code for me. That said, I'm forced to frame the page (same domain) and use some JavaScript to modify its contents... Right now, I'm trying to find anchor tags which contain a URL and set the target attribute to "_top". This way, anchors on the page which open menus etc are loaded within the frame, and anything that points offsite is loaded in the overall window. Here's what I've tried:

function pointOutside(){
    var anchorS = window.frames[0].document.getElementsByTagName("a");
    for(i=0;i<anchorS.length;i++){
        var foo = anchorS[i].getAttribute('href');
        foo = foo.toString();
        if(foo.search(/http/i) != -1){
            anchorS[i].setAttribute('target','_top');
        };
    };
};
setTimeout("pointOutside()",2000);

The timeout gives the frame's contents sufficient time to load before it's called, but where I'm running into trouble is checking the href property for whether or not it starts with "http". I initially tried this without the "foo = foo.toString();" line, but was getting an error along the lines of "Uncaught TypeError: Cannot call method 'search' on null." I thought to myself, "aha, I'll make sure it's a string!" but no luck. Now I'm getting a similar error when I call toString()... "Uncaught TypeError: Cannot call methor 'toString' of null."

The odd thing is that, to make sure my selector was working, I used "alert(foo)" and was able to get a popup for each anchor tag showing the value for the href property.

Not sure where I'm going wrong here. Any help would be MUCH appreciated.

First off, if you have any javascript frameworks available in that browser window, take advantage of them by using a DOMReady function like jQuery's .ready http://api.jquery.com/ready/

Also, you'll need to account for .href and .getAttribute('href') returning different values. In Chrome for example, .href returns the url that will be navigated to if you clicked the link. .getAttribute('href') however returns what's actually in the anchor tag, which may be a relative url.

Lastly, the reason you are getting the exception is that there are probably some anchors on the page that do not have an href and are there for purely structural purposes. For those elements, you could insert a line before you try and use .toString() like so:

if (typeof foo !== "string") { continue; }

The continue statement causes the for loop to ignore that link and move on to the next iteration of the loop if the href is not set on that link.

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