FoxyFish
FoxyFish

Reputation: 892

jquery find and replace iframe src

I need to load a url in an iframe on page load (which is working), then grab the whole url of that loaded iframe, then once the url is saved as a variable i want to find any text between "target" and "/" (example url http://www.example.com/user/target09576/index.php i wish to find the 09576) then redirect the whole page using the found text (09576) as part of the redirect url.

I know, bad explanation and not a great solution, but any help would be appreciated.

$(document).ready(function() {
        var iframe = $('#wmif');
        var url = '<? echo "".$redirectlocation.""; ?>';
        iframe.attr('src', url);
        var searchurl = iframe.contentWindow.location;
        var rep = /(.*target\s+)(.*)(\s+\/.*)/;
        var target = searchurl.replace(rep, '$2');
        window.location = 'http://example.com/go/index.php?target='+target;
}); 

well the iframe loads the new location ok, but it doesn't do any of the rest.

Upvotes: 0

Views: 252

Answers (2)

hex494D49
hex494D49

Reputation: 9235

Yet another solution

var matches = /target\s?([^\/]+)/.exec('http://www.domain.com/user/target09576/index.php')

or

var matches = /(?:target\s?)([^\/]+)/.exec('http://www.domain.com/user/target09576/index.php')
console.log(matches[1]);    //  09576

Modify regex to this /(?:target)([^\/]+)/ if you don't expect a space between target and the number.

Upvotes: 1

MattSizzle
MattSizzle

Reputation: 3175

I would do it similar to the below, same result but with jQuery and an updated regex

$(document).ready(function () {
    var iframe = $('#wmif');
    var url = ''<? echo "".$redirectlocation.""; ?>';
    iframe.attr('src', url);
    //var searchurl = iframe.contentWindow.location; <- Invalid
    console.log($('#wmif').contents().get(0).location);
    var searchurl = $('#wmif').contents().get(0).location.href;
    console.log(searchurl);
    var rep = /.*\/target(\w+)\/.*/;
    var target = searchurl.replace(rep, '$1');    
    console.log(target);
    window.location = 'http://domain.com/go/index.php?target=' + target;
});

Upvotes: 1

Related Questions