Any good debugger for HTML5 Javascript postMessage

2019-02-07 22:37发布

问题:

Is there any good tool out there that allows developers to correctly debug messages sent between windows with postMessage?

Or maybe a plugin for Firebug?

回答1:

Firebug (as of 1.11 beta 1) supports this with monitorEvents(). You can do something like this:

$("iframe").each(function(i, e) {
    console.log("Monitoring messages sent to: iframe(" + i + ")#" + $(this).attr("id"));
    monitorEvents(this.contentWindow, "message"); 

    // Send a test message to this iframe
    this.contentWindow.postMessage("Hi iframe - " + i, "*"); 
});

console.log("Monitoring messages sent to window");
monitorEvents(window, "message"); 
// Send a test message to the window
window.postMessage("Hi window", "*"); 

(@Pierre: thanks for mentioning that feature request)

EDIT: Also works in Chrome, though when I tried the above code I encountered a security error that the document.domain values were not the same, so the behavior of these two implementations may be slightly different.

UPDATE: I have submitted a feature request to the Chrome team asking that postMessage events appear in the timeline. Also, I found an extension called JScript Tricks that can inject arbitrary JavaScript code into a page when it is loaded. You can add the following code to it to monitor events once the page loads. It works pretty well, though it might miss events that occur immediately (e.g. before onload, if that's possible).

(function($) {
    var $window = $(window);
    $window.add("iframe").on("message", function(e) {
        console.log("Received messsage from " + e.originalEvent.origin + ", data = " + e.originalEvent.data);
    });
})(jQuery);


回答2:

A firebug feature-request has been issued.