使用 javascript 从上一页获取 URL



我的页面A和B.在我的页面A中,我有指向页面B的链接。我想做的是,当我单击页面 A 中的链接时,它将打开页面 B,并给我页面 A 的 URL 警报。这是我尝试的:

页 A:

<html>
<head>
<a href="file:///C:/Users/jason/Desktop/pageb.html">click me</a> 
</head>
</html>

B页:

<html>
<head>
<script type="text/javascript">
var oldURL = document.referrer;
alert(oldURL);
</script>
</head>

当我单击它时,它会打开页面 B,但警报是空白的。我该怎么做?

 alert(document.referrer);

这应该会提醒引荐来源网址。

注意:我将其从评论中移出,因为它描述了真正的问题。

代码的原始问题与您用于页面 B 的file:/// URI 有关。不会有referrer.但是,如果您从服务器运行此代码,则可以正常工作。这是证据:Plunkr

从文件系统加载文件(使用file://协议(时,不会设置 referrer 标头。如果在开发工具中打开网络面板并查看两个页面的标题,则可以轻松看到差异。打开时没有file:///标题,来自 Plunkr 有正确的referrer标题。

所以你的代码工作正常(但应该移动锚标记(。

你不需要做window.open((或使用本地存储或任何类似的事情。

您可以将

最近访问的网址保存在会话存储中在 A 页上:

sessionStorage.setItem('url', window.location.href);

在 B 页上

alert(sessionStorage.getItem('url'))

<a href="file:///C:/Users/jason/Desktop/pageb.html">click me</a>head标记中添加。并打印oldURL变量而不是window.location.href当前 URL。

页 A

<html>
<head>
</head>
<a href="file:///C:/Users/jason/Desktop/pageb.html">click me</a> 
</html>

页 B

var oldURL = document.referrer;
alert(oldURL);

您可以在 URL 中传递它:

 window.open("b.html?referer=" + window.location.href);

您还可以使用 opener 对象来获取父窗口的变量:

答.html

<html>
 <script>
   var referrer = window.location.href;
   var win = window.open("b.html");
 </script>
</html>

乙.html

<html>
 <script>
   alert(window.opener.referrer);
 </script>
</html>

如上所述@RandyCasburn,您还必须将标签从头部移动到身体才能看到:

<html>
<head>
</head>
<body>
    <a href="file:///C:/Users/jason/Desktop/pageb.html">click me</a> 
</body>
</html>

您可以使用 document.referrer

参考以下代码片段

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Alert</title>
</head>
<body>
    <a href="https://www.google.co.in/" onclick="onLinkClick()">Link</a>
    <script>
        function onLinkClick() {
            alert("Redirected from==>"+document.referrer);
        }
    </script>
</body>
</html>

最新更新