Search code examples
javascriptjqueryfacebookdom-events

Post comments on Facebook page via console


Like in the image, the Facebook comment box has no submit button, when you write something and press Enter button, the comment posted.

I want to submit the comment via JavaScript that running in console, but I tried to trigger Enter event, submit event of the DOM. Could not make it work.

Facebook comment box


Solution

  • The current comment boxes aren't a traditional <textarea> inside of a <form>. They're using the contenteditable attribute on a div. In order to submit in this scenario, you'd want to listen to one of the keyboard events (keydown, keypress, keyup) and look for the Enter key which is keycode 13.

    Looks like FB is listening to the keydown evt in this case, so when I ran this code I was able to fake submit a comment:

    function fireEvent(type, element) {
        var evt;
    
        if(document.createEvent) {
            evt = document.createEvent("HTMLEvents");
            evt.initEvent(type, true, true);
        } else {
            evt = document.createEventObject();
            evt.eventType = type;
        }
    
        evt.eventName = type;
        evt.keyCode = 13;
        evt.which = 13;
    
        if(document.createEvent) {
            element.dispatchEvent(evt);
        } else {
            element.fireEvent("on" + evt.eventType, evt);
        }
    }
    
    fireEvent('keydown', document.querySelector('[role="combobox"]._54-z span span'));
    

    A couple of things to note about this. The class ._54-z was a class they just happened to use on my page. Your mileage may vary. Use dev tools to make sure you grab the right element (it should have the aria role "combobox"). Also, if you're looking to support older browsers, you're going to have to tweak the fireEvent function code above. I only tested the above example in the latest Chrome.

    Finally, to complicate matters on your end, Facebook is using React which creates a virtual DOM representation of the current page. If you're manually typing in the characters into the combobox and then run the code above, it'll work as expected. But you will not be able to set the combobox's innermost <span>'s innerHTML to what you're looking to do and then trigger keydown. You'll likely need to trigger the change event on the combobox to ensure your message persists to the Virtual DOM.

    That should get you started! Hope that helps!