如何将正确的网址传递给iframe页面?

时间:2012-01-15 13:58:37

标签: javascript iframe location

我的网站支持以下网址:

(1) http://mysite.example.com/section/ - main page
(2) http://mysite.example.com/section/#page2
(3) http://mysite.example.com/section/surname-name-middlename/
(4) http://mysite.example.com/section/surname-name-middlename/#page2
(5) http://mysite.example.com/section/add

现在我正在尝试将我的网站显示为另一个网站上的iframe。该站点支持setLocationonLocationChanged方法来定义哈希,并在相应更改哈希时做出反应。

我为所有网页定义了setLocation,这里没问题。因此,第三方网站上面的链接如下所示:

(1) http://3rdpartysite.com/mypage
(2) http://3rdpartysite.com/mypage#page2
(3) http://3rdpartysite.com/mypage#surname-name-middlename
(4) http://3rdpartysite.com/mypage#surname-name-middlename,page2
(5) http://3rdpartysite.com/mypage#add

但现在我正在努力实现正确的onLocationChanged行为。

section是所有网页的常见部分。

我试图在主页上执行以下操作(并且不支持上面的选项(4)):

// location here is everything after # in url: http://3rdpartysite.com/mypage#...
function onLocationChanged(location) { 
  if (location.indexOf('page')>-1) {
    window.location.href = '#'+location;
  } else if (location == 'add') {
      window.location.href = window.location.host + window.location.pathname + '/add';
    } else if (location != '') {
        window.location.href = window.location.host + window.location.pathname + '/'+location+'/';
      }
}

但它无法正常工作。我的方法出了什么问题?

1 个答案:

答案 0 :(得分:0)

以下是主页上正常运行的代码:

function onLocationChanged(loc) {
    var url = window.location.protocol + '//' + window.location.host + window.location.pathname;
    if (loc.indexOf('page') > -1 && loc.indexOf(',page') == -1) {
        window.location.href = '#' + loc;
    } else if (loc == 'add') {
        window.location.href = url + 'add';
    } else if (loc != '' && loc.indexOf(',page') > -1) {
        window.location.href = url + '' + loc.split(',', 2)[0] + '/#' + loc.split(',', 2)[1];
    } else if (loc != '') {
        window.location.href = url + '' + loc + '/';
    }
}

这是其他页面的代码(没有选项(4)支持):

function onLocationChanged(loc) {
  var url = window.location.protocol + '//' + window.location.host + '/' + window.location.pathname.split('/',3)[1] + '/';
  if (loc.indexOf('page')>-1) {
    window.location.href = url + '#' + loc;
  } else if (loc == 'add') {
      window.location.href = url + 'add';
    } else if (loc != '') {
        window.location.href = url + '' + loc + '/';
      }
}

不知道如何使它变得普遍。