0

我需要在单个变量中获取当前网页 url,例如:

var x = window.location.href;

但问题是脚本有时会在跨域 Iframe中使用,有时会在同一个域中使用。由于window.location.href在跨域 iframe 中不起作用,所以我已经测试 x = document.referrer了跨域 iframe(只读)并且它工作正常。但是我需要在一个变量中同时使用这两个选项,这样我就可以通过.match()Javascript 中的方法在 url 验证中使用它。

我试图像这样结合,但它不起作用

    var x = window.location.href;
if (typeof(window.location.href) === 'undefined') {
    x = document.referrer;
}

我的完整代码在这里:

//获取 url - 这部分不起作用

var x = window.location.href;
if (typeof(window.location.href) === 'undefined') {
    x = document.referrer;
}

//网址验证-- 这部分工作正常

var y = "zebra";
var rgxp = new RegExp(y, "gi");
if (x.match(rgxp) > -1) {
    alert('Found a zebra in url');

我不知道是否真的可以合并,但否则我想我必须重复这个脚本两次。1 用于跨域 Iframe,而 2 用于同一域。

我是 Javascript 的新手并且被困在这里,所以任何帮助和方向都将是救命稻草

4

0 回答 0