Okay, that error Uncaught TypeError: Cannot redefine property: href means that in the specific browser environment the script is running, the href property of the window.location object is not configurable.
This is a security measure implemented by browsers. Object.defineProperty can only redefine properties if their configurable attribute is set to true. For sensitive properties like window.location.href, browsers often set this to false to prevent malicious scripts from completely changing how the property works.
This means the approach of using Object.defineProperty to override the href setter doesn't work in your environment.
However, overriding the location.assign() and location.replace() methods often still works because these methods might be defined differently by the browser (e.g., as a writable property holding a function, rather than a non-configurable accessor property).
Here's an updated version of the userscript that keeps the working parts (blocking assign and replace) and gracefully handles the failure for href by skipping that specific override and logging a message:
// ==UserScript==
// @name Stop Redirects via location methods
// @namespace http://tampermonkey.net/
// @version 0.2
// @description Attempts to prevent JavaScript from redirecting pages using location.assign() or location.replace(). Note: Blocking location.href = '...' may not be possible due to browser restrictions.
// @author You
// @match *://*/* // Applies to all websites; change to specific domains if needed, e.g., *://*.example.com/*
// @grant none
// @run-at document-start // Runs as early as possible to intercept redirects
// ==/UserScript==
(function() {
'use strict';
let hrefBlockingPossible = false;
// Attempt to override location.href setter - This part often fails due to browser security
try {
const locationObj = window.location;
const originalHrefDescriptor = Object.getOwnPropertyDescriptor(locationObj, 'href');
if (originalHrefDescriptor && originalHrefDescriptor.configurable) {
// If it's configurable, we *can* redefine it
Object.defineProperty(locationObj, 'href', {
get: function() {
// Use the original getter to return the current value
return originalHrefDescriptor.get.call(locationObj);
},
set: function(url) {
// Block the setter: Do nothing, but log the attempt
console.warn('Userscript: Blocked redirection attempt: location.href set to ' + url);
// You could add logic here to allow redirects under certain conditions
},
configurable: true // Keep configurable true if we succeeded
});
hrefBlockingPossible = true;
console.log('Userscript: Successfully hooked location.href setter.');
} else if (originalHrefDescriptor && !originalHrefDescriptor.configurable) {
// Property exists but is not configurable - This is the common case causing the error
console.warn('Userscript: Cannot redefine location.href setter because the property is not configurable in this browser/context.');
} else {
// Should not happen for location.href, but included for robustness
console.warn('Userscript: Could not get property descriptor for location.href.');
}
} catch (error) {
// Catch any unexpected errors during the override attempt
console.error('Userscript: Failed to override location.href setter:', error);
}
// Override location.assign()
// This part is more likely to succeed
if (window.location.assign) {
const originalAssign = window.location.assign;
window.location.assign = function(url) {
console.warn('Userscript: Blocked redirection attempt: location.assign(' + url + ')');
// To allow conditionally, add logic here and call:
// originalAssign.call(window.location, url);
};
console.log('Userscript: Successfully hooked location.assign().');
} else {
console.warn('Userscript: location.assign() not found or accessible.');
}
// Override location.replace()
// This part is also more likely to succeed
if (window.location.replace) {
const originalReplace = window.location.replace;
window.location.replace = function(url) {
console.warn('Userscript: Blocked redirection attempt: location.replace(' + url + ')');
// To allow conditionally, add logic here and call:
// originalReplace.call(window.location, url);
};
console.log('Userscript: Successfully hooked location.replace().');
} else {
console.warn('Userscript: location.replace() not found or accessible.');
}
if (!hrefBlockingPossible) {
console.warn('Userscript: Redirect blocking for location.href = "..." is likely not working.');
} else {
console.log('Userscript: Redirect blocking for location.href, assign, and replace is active (where supported).');
}
})();
Changes Made:
- Added a
try...catch block specifically around the Object.defineProperty call for location.href to catch the TypeError.
- Inside the
try block, added a check originalHrefDescriptor.configurable. The defineProperty call only happens if the property is reported as configurable.
- Added more specific console logs to indicate which overrides were successful or failed.
- Updated the overall description and comments to reflect that blocking
location.href = '...' might not work.
With this revised script, the TypeError should no longer stop the script execution. It will still attempt to block location.href = ... but will fail silently (with a console warning) if the property is non-configurable, while continuing to successfully block location.assign() and location.replace().