如何用JavaScript获取前一页URL?实现跳转后弹出来源页地址
Hey there! Let's sort out your goal: you want Page B to pop up Page A's URL when opened via a link from Page A.
First, let's break down why your current code might not be working. You're loading pages via the file:// protocol (local files), and most modern browsers block document.referrer for local files due to security restrictions. That's likely why your alert is showing an empty string instead of Page A's URL.
Here are two reliable solutions to make this work:
Solution 1: Pass Page A's URL as a Query Parameter
This method works for both local files and server-hosted pages, since we explicitly send the URL along with the link.
Page A Code:
<html> <body> <!-- Encode the current page's URL to handle special characters, then pass it as a 'from' parameter --> <a href="pageb.html?from=${encodeURIComponent(window.location.href)}">click me</a> </body> </html>
Page B Code:
<html> <head> <script type="text/javascript"> // Parse the URL parameters to extract the 'from' value const urlParams = new URLSearchParams(window.location.search); const oldURL = urlParams.get('from'); alert(oldURL); </script> </head> <body> <!-- Your Page B content goes here --> </body> </html>
Solution 2: Serve Pages via a Local HTTP Server
If you prefer to keep using document.referrer like your original code, serve your pages over http:// instead of file://. Browsers allow document.referrer for HTTP requests, so your initial code will work as intended.
For example, using Python's built-in HTTP server:
- Open a terminal, navigate to the folder where
pagea.htmlandpageb.htmlare stored. - Run this command:
python -m http.server 8000
- Open your browser and visit
http://localhost:8000/pagea.html, then click the link. Page B will alert Page A's URL using your originaldocument.referrercode!
A quick side note: The file:// protocol's referrer blocking is an intentional security feature—it prevents local file paths from being exposed to other local files, so it's not a bug in your code.
内容的提问来源于stack exchange,提问作者raspi surya

