Search code examples
google-chromehtml5-videogoogle-chrome-devtoolsuserscripts

Why can I change HTMLMediaElement.prototype.play from console, but not via user script?


If I open the Chrome developer tools console and change HTMLMediaElement.prototype.play, it works just fine.

> HTMLMediaElement.prototype.play = function(){debugger;}
function (){debugger;}
> HTMLMediaElement.prototype.play
function (){debugger;}

However, if I change it from a user script, the function always seems to revert to the native implementation.

> HTMLMediaElement.prototype.play
function play() { [native code] }

I have verified that the user script loads correctly, and I even tried an ugly setInterval approach, to see if at least that works:

var myFunction = function(){debugger;};
window.setInterval(function(){
  if (window.HTMLMediaElement.prototype.play != myFunction)
    window.HTMLMediaElement.prototype.play = myFunction;
}, 900);

But even with this I always end back up with the native implementation.


Solution

  • From Injecting JS functions into the page from a Greasemonkey script on Chrome:

    The only way to communicate with the code running on the page in Chrome is through the DOM, so you'll have to use a hack like inserting a tag with your code. Note that this may prove buggy if your script needs to run before everything else on the page.

    EDIT: Here's how the Nice Alert extension does this:

    function main () {
      // ...
      window.alert = function() {/* ... */};
      // ...
    }
    
    var script = document.createElement('script');
    script.appendChild(document.createTextNode('('+ main +')();'));
    (document.body || document.head || document.documentElement).appendChild(script);