Skip to content

Instantly share code, notes, and snippets.

@ounissi-zakaria
Created March 22, 2024 21:08
Show Gist options
  • Save ounissi-zakaria/043ccfeb35e248aabe779581feb9d174 to your computer and use it in GitHub Desktop.
Save ounissi-zakaria/043ccfeb35e248aabe779581feb9d174 to your computer and use it in GitHub Desktop.
User Script that tracks postMessage event listeners and makes it easy to track/debug them
// ==UserScript==
// @name PostMessage Tracker
// @namespace Violentmonkey Scripts
// @match *://*/*
// @version 1.0
// @author Ounissi zakaria (https://twitter.com/zakaria_ounissi)
// @description Each time an event listener is added for `message` it adds a menu command to tha message handler.
// @grant GM.registerMenuCommand
// @run-at document-start
// ==/UserScript==
// Create a variable to store the original addEventListener method
var originalAddEventListener = unsafeWindow.addEventListener;
function onClick(listener) {
return (function () {
console.log(listener)
const handler = {
get(target, prop, receiver) {
console.trace("Tracing postMessage listener", prop)
debugger;
return Reflect.get(...arguments);
},
};
e = new Proxy({ data: { milk: true }, origin: "https://z98.pro", lastEventId: "989898", source: "1", ports: ["1"] }, handler);
console.log(listener(e))
})
}
// Override the addEventListener method
unsafeWindow.addEventListener = function (type, listener, options) {
// Call the original addEventListener method
originalAddEventListener.apply(this, arguments);
if (arguments[0].toLowerCase() === "message") {
GM.registerMenuCommand(listener.toString(), onClick(listener))
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment