如何在网站尝试修改location对象时触发控制台错误并阻止页面重定向
onbeforeunload Got it, let's cut to the chase—you want to stop those location = 'http://example.com/' or location.href = 'http://example.com/' redirects dead in their tracks, and see the target URL before any navigation happens, no clunky onbeforeunload workarounds needed. Here's a direct, reliable approach that hijacks the location object itself:
Core Idea
When you assign a URL to location or location.href, you're triggering the setter method of the href property on the Location object. We can override this setter to intercept the redirect attempt, log the target URL, and block the navigation entirely.
Working Code
Add this script as early as possible in the page (e.g., in the <head> before other scripts, or use a userscript with @run-at document-start to ensure it loads first):
// Save the original href setter to reference if needed later const originalHrefSetter = Object.getOwnPropertyDescriptor(Location.prototype, 'href').set; // Override the href property's setter on the Location prototype Object.defineProperty(Location.prototype, 'href', { set: function(targetUrl) { // Log the target URL to your console immediately console.log('🔴 Redirect attempt detected:', targetUrl); // Throw an error to block the redirect and make it visible in the console throw new Error(`Redirect blocked: ${targetUrl}`); // If you want silent blocking (no console error), just omit the throw statement // and don't call originalHrefSetter(targetUrl) }, get: function() { // Keep the original getter behavior intact return Object.getOwnPropertyDescriptor(Location.prototype, 'href').get.call(this); } }); // Optional: Block location.replace() redirects too const originalReplace = Location.prototype.replace; Location.prototype.replace = function(targetUrl) { console.log('🔴 Replace redirect attempt detected:', targetUrl); throw new Error(`Replace redirect blocked: ${targetUrl}`); // Omit originalReplace(targetUrl) to block silently };
How It Works
- Covers all href assignments: Both
location.href = "url"and directlocation = "url"calls trigger thehrefsetter, so this handles both cases you mentioned. - Logs URLs instantly: You'll see the target URL in the console before any navigation can start—no waiting for unload events or workarounds.
- Blocks redirects reliably: Throwing an error interrupts the code flow that's trying to redirect, and since we don't call the original setter, the browser never processes the navigation request.
Key Notes
- Load order is critical: This script must execute before any redirect-triggering code. If testing in the browser console, run this snippet first, then trigger the redirect.
- Silent blocking available: If you don’t want console error messages, remove the
throwstatement and avoid calling the original setter/replace method. The redirect will be blocked without any visible feedback. - Handle additional redirect methods: The optional
replaceoverride covers sites that uselocation.replace()instead of directlocation/hrefassignments.
内容的提问来源于stack exchange,提问作者oleedd

