The error occurs because location.href is a non-configurable property in many browsers, which means it cannot be redefined using Object.defineProperty(). Here's an updated approach that works around this limitation:
// ==UserScript==
// @name Stop Redirects via location.href
// @namespace http://tampermonkey.net/
// @version 0.2
// @description Prevents JavaScript from redirecting pages using location.href, location.assign(), or location.replace().
// @author You
// @match *://*/*
// @grant none
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
// Store the original location object
const originalLocation = window.location;
const originalHref = originalLocation.href;
// Create a proxy for the location object
const locationProxy = new Proxy(originalLocation, {
get(target, prop) {
// Return original values for getters
if (prop === 'href') {
return originalHref;
}
// For methods, return our wrapped versions
if (prop === 'assign') {
return function(url) {
console.warn('Blocked redirection attempt: location.assign(' + url + ')');
};
}
if (prop === 'replace') {
return function(url) {
console.warn('Blocked redirection attempt: location.replace(' + url + ')');
};
}
// Return original property/method for everything else
return target[prop];
},
set(target, prop, value) {
if (prop === 'href') {
console.warn('Blocked redirection attempt: location.href = ' + value);
return true; // Indicate success without actually setting
}
// Allow other properties to be set normally
target[prop] = value;
return true;
}
});
// Try to override window.location with our proxy
try {
Object.defineProperty(window, 'location', {
get() { return locationProxy; },
set(v) {
console.warn('Blocked attempt to replace window.location object');
return true;
},
configurable: false
});
} catch (e) {
// If we can't override window.location, try a different approach
console.warn('Could not override window.location, trying alternative method');
// Alternative: Override the methods directly
const originalAssign = window.location.assign;
const originalReplace = window.location.replace;
// Wrap in try-catch as these might also be non-configurable
try {
window.location.assign = function(url) {
console.warn('Blocked redirection attempt: location.assign(' + url + ')');
};
} catch (e) {
console.error('Could not override location.assign');
}
try {
window.location.replace = function(url) {
console.warn('Blocked redirection attempt: location.replace(' + url + ')');
};
} catch (e) {
console.error('Could not override location.replace');
}
// For href, we'll need to monitor it differently
// This approach uses a MutationObserver to detect meta refresh tags
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
if (node.tagName === 'META' && node.httpEquiv === 'refresh') {
node.remove();
console.warn('Blocked meta refresh redirect');
}
});
});
});
// Start observing when DOM is ready
if (document.head) {
observer.observe(document.head, { childList: true });
} else {
document.addEventListener('DOMContentLoaded', function() {
observer.observe(document.head, { childList: true });
});
}
}
// Additional protection: Override common redirect functions
// Some sites use window.navigate (IE-specific but sometimes polyfilled)
if (window.navigate) {
window.navigate = function(url) {
console.warn('Blocked redirection attempt: window.navigate(' + url + ')');
};
}
// Block window.location = "url" syntax
let locationSetterBlocked = false;
Object.defineProperty(window, 'location', {
get() { return originalLocation; },
set(value) {
if (!locationSetterBlocked) {
console.warn('Blocked redirection attempt: window.location = ' + value);
locationSetterBlocked = true;
setTimeout(() => { locationSetterBlocked = false; }, 100);
}
return true;
}
});
console.log('Userscript: Redirect blocking is active.');
})();
If you're still getting errors, here's an even simpler version that focuses on the methods that can be overridden:
// ==UserScript==
// @name Stop Redirects (Simple)
// @namespace http://tampermonkey.net/
// @version 0.3
// @description Prevents JavaScript redirects by overriding common redirect methods
// @author You
// @match *://*/*
// @grant none
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
// Store original methods
const originalAssign = window.location.assign;
const originalReplace = window.location.replace;
const originalReload = window.location.reload;
// Override location.assign
window.location.assign = function(url) {
console.warn('Blocked redirection attempt: location.assign(' + url + ')');
// Uncomment next line to allow the redirect:
// originalAssign.call(window.location, url);
};
// Override location.replace
window.location.replace = function(url) {
console.warn('Blocked redirection attempt: location.replace(' + url + ')');
// Uncomment next line to allow the redirect:
// originalReplace.call(window.location, url);
};
// Override location.reload to prevent refresh-based redirects
window.location.reload = function(forcedReload) {
console.warn('Blocked reload attempt');
// Uncomment next line to allow the reload:
// originalReload.call(window.location, forcedReload);
};
// Block meta refresh tags
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
if (node.tagName === 'META' && node.httpEquiv && node.httpEquiv.toLowerCase() === 'refresh') {
node.remove();
console.warn('Blocked meta refresh redirect');
}
});
});
});
// Start observing as soon as possible
if (document.documentElement) {
observer.observe(document.documentElement, { childList: true, subtree: true });
} else {
// Fallback for very early execution
const startObserver = () => {
observer.observe(document.documentElement, { childList: true, subtree: true });
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startObserver);
} else {
startObserver();
}
}
console.log('Userscript: Redirect blocking is active (simple version).');
})();
This simpler version:
- Only overrides methods that are typically configurable (
assign, replace, reload)
- Doesn't attempt to override
location.href directly since it's often non-configurable
- Includes protection against meta refresh tags
- Should work without throwing errors
Note that this won't catch all redirect attempts (particularly direct location.href = "..." assignments), but it will catch many common redirect patterns without causing errors.