问题
If a javascript function is declared anonymously is there any way to override it or portions of it?
I am attempting to stop google.com's instant search from hijacking the up and down arrow keys to move through your search rankings. I have identified what I believe is the problematic section of code. Keycodes 38 and 40 are for the down and up keys.
if (b == 40) aa(f);
else if (b == 38) aa(j);
else if (b == 37 || b == 39) if (!ca(b == 39)) return f;
a.preventDefault && a.preventDefault();
return a.returnValue = j
The problem is that this is part of a function called Sb = function (a) {} that lies inside of about a three thousand line anonymous function. There is a similar question posted on SO here that the author ended up working out in a hacky way that doesn't apply to me. I realize I can turn off instant search, but I like it, I just can't stand that my arrow keys don't work anymore.
SOLUTION:
I ended up writing a chrome extension to revert up/down arrow key functionality to scrolling. I used the following code. Thank you to Raze and Mofle.
if (event.keyCode == 40 || event.keyCode == 38) {
event.cancelBubble = true;
event.stopPropagation();
return false;
}
回答1:
You can't override an anonymous function inside another anonymous function. You can't change portions of any existing function, you'll have to create a new function and attach it where required, though you could get the source of a function, manipulate it and create a new function out of the source.
I have two suggestions for this problem here, which doesn't involve redefining the functions.
- Add an event listener for the input text box at the capture phase, and cancel the event if keyCode is UP or DOWN
- Create an overlayed text box where you actually enter text, and pass on all events except UP key and DOWN key to the actual text box underneath.
回答2:
You can easily do that by capturing arrow key events and preventing them from bubbling.
window.addEventListener('keydown', function(e) {
e.stopPropagation();
}, true);
Tested and works on google.com
回答3:
Remove all event listeners from the element by replacing it with a clone of itself (node.parentNode.replaceChild(node.cloneNode(true), node)) and then apply a manually modified version of Google's JavaScript code (document.documentElement.appendChild(document.createElement("script")).src="location of your modified script").
回答4:
Try using a hard core replace before the function is executed.
document.body.innerHTML = document.body.innerHTML.replace(/if (b == 40) aa(f);/,'').replace(/else if (b == 38) aa(j);/,'').replace(/else if (b == 37 || b == 39) if (/a.preventDefault && a.preventDefault();/,'').replace(/return a.returnValue = j/,'')
Probably it will work
来源:https://stackoverflow.com/questions/4201215/overriding-a-portion-of-a-google-com-anonymous-function