Search code examples
javascriptreverse-engineering

When reverse engineering code to make a web page plugin, how can I find what function is called when a certain element receives an event?


I run into this problem quite often when I decide to try tinkering with a 3rd party site for a browser plugin, let's say I want to make a simple auto-play plugin for a video site that doesn't have an autoplay feature. There's a UI element that I know triggers their internal function for playing the video, but I dont know how to identify that function by inspecting the element in the console.

What tricks / methods can I use to be able to trigger that function manually without the user actually clicking the element?


Solution

  • If you know that clicking a button or an element somewhere results in the video playing, often it'll be simple enough to just call .click() on that button.

    With the mouse hovered over the element with the functionality, right click and Inspect at that point, and the Elements panel of the developer console should bring you to the element the mouse is over. Figure out a selector or a process to uniquely identify the element, and then .click() it, eg

    document.querySelector('.video-container .play-button').click();
    

    You also may need to wait for the video container / play button to be created in the DOM first, in which case you can use MutationObserver or a setInterval to wait for the site to be ready.

    An alternative, trickier method is to, when inspecting the element, go to the Event Listeners panel, and look for listeners attached to click / mousedown (etc) events. Sometimes, these functions are callable from the global scope, in which case you can call those functions directly instead of clicking the element.

    If the function isn't callable from the global scope, a hacky method to get a reference to it anyway is to monkeypatch addEventListener before the page loads, listen for when the listener you want gets attached, and then call the function passed. (But the earlier methods are much simpler and preferable when possible)