Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 814
Hank X Avatar asked Jun 26 '15 16:06

Hank X


People also ask

How do I comment on my Facebook business page from my desktop?

Go to the Page post you want to like or comment on. Tap your profile picture in the bottom-right corner of the post. Select the Page you want to like or comment as. Like or comment on the post.

How do I manage comments on my Facebook business page?

Currently there is no way to moderate comments on Facebook business page's. This means any comment posted will be visible, there is no way of keeping a comment private until you view it and approve it.


3 Answers

as I wasn't able to post comments through the "normal" facebook page, I remembered that they also have the mobile version, which is on m.facebook. com, there, they still have the submit Button, so depending on your needs, this may be a good option

so, you could go to the mobile facebook post (eg https://m.facebook.com/${author}/posts/${postId}) and do

// Find the input element that saves the message to be posted
document.querySelector("input[name='comment_text']").value='MESSAGE TO POST';
// find the submit button, enable it and click it
const submitButton = document.querySelector("button[name='submit']");
submitButton.disabled = false;
submitButton.click();
like image 97
Marcelo Cardozo Avatar answered Sep 26 '22 10:09

Marcelo Cardozo


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!

like image 30
Benjamin Solum Avatar answered Sep 25 '22 10:09

Benjamin Solum


Some years after, this post remains relevant and is actually the only one I found regarding this, whilst I was toying around trying to post to FB groups through JS code (a task similar to the original question).

At long last I cracked it - tested and works:

  setTimeout(() => {
        document.querySelector('[placeholder^="Write something"]').click();
        setTimeout(() => {
            let postText = "I'm a Facebook post from Javascript!";
            let dataDiv = document.querySelector('[contenteditable] [data-offset-key]');
            let dataKey = dataDiv.attributes["data-offset-key"].value;
            //Better to construct the span structure exactly in the form FB does it
            let spanHTML = `<span data-offset-key="${dataKey}"><span data-text="true">${postText}</span></span>`;
            dataDiv.innerHTML = spanHTML;

            let eventType = "input";
            //This can probably be optimized, no need to fire events for so many elements
            let div = document.querySelectorAll('div[role=presentation]')[1].parentElement.parentElement;
            let collection = div.getElementsByTagName("*");
            [...collection].forEach(elem => {
                let evt = document.createEvent("HTMLEvents");
                evt.initEvent(eventType, true, true); //second "true" is for bubbling - might be important
                elem.dispatchEvent(evt);
            });
            //Clicking the post button
            setTimeout(()=>{
                document.querySelector('.rfloat button[type=submit][value="1"]').click();
            },2000);
        }, 4000);
    }, 7000);

So here's the story, as I've learned from previous comments in this post and from digging into FB's code. FB uses React, thus changes to the DOM would not "catch on" as React uses virtual DOM. If you were to click "Post" after changing the DOM from JS, the text would not be posted. That's why you'd have to fire the events manually as was suggested here.

However - firing the right event for the right element is tricky business and has almost prevented me from succeeding. After some long hours I found that this code works, probably because it targets multiple elements, starting from a parent element of the group post, and drilling down to all child elements and firing the event for each one of them (this is the [...collection].forEach(elem => { bit). As written this can be obviously be optimized to find the one right element that needs to fire the event.

As for which event to fire, as was discussed here, I've experimented with several, and found "input" to be the one. Also, the code started working after I changed the second argument of initEvent to true - i.e. evt.initEvent(eventType, true, true). Not sure if this made a difference but I've had enough hours fiddling with this, if it works, that enough for me. BTW the setTimeouts can be played around with, of course.

(Unsuccessfully) Digging into FB's React Data Structure

Another note about a different path I tried to go and ended up being fruitless: using React Dev Tools Chrome extension, you're able to access the components themselves and all their props and states using $r. Surprisingly, this also works outside of the console, so using something like TamperMonkey to run JS code also works. I actually found where FB keeps the post text in the state. For reference, it's in a component called ComposerStatusAttachmentMentionsInputContainer that's in charge of the editor part of the post, and below is the code to access it.

$r actually provides access to a lot of React stuff, like setState. Theoritically I believed I could use that to set the state of the post text in React (if you know React, you'd agree that setState would be the right way to trigger a change that would stick).

However, after some long hours I found that this is VERY hard to do, since FB uses a framework on top of React called Draft.js, which handles all posts. This framework has it's own methods, classes, data structures and what not, and it's very hard to operate on those from "outside" without the source code.

I also tried manually firing the onchange functions attached to the components, which didn't work because I didn't have the right parameters, which are objects in the likes of editorContent and selectionContent from Draft.Js, which need to be carefully constructed using methods like Modifier from Draft.js that I didn't have access to (how the hell do you externally access a static method from a library entangled in the source code?? I didn't manage to).

Anyway, the code for accessing the state variable where the text is stored, provided you have React dev tools and you've highlighted ComposerStatusAttachmentMentionsInputContainer:

let blockMap = $r["state"].activeEditorState["$1"].currentContent.blockMap;
let innerObj = JSON.parse(JSON.stringify(blockMap)); //this is needed to get the next property as it's not static or something

let id = Object.keys(innerObj)[0]; //get the id from the obj property 
console.log(innerObj[id].text); //this is it!

But as I wrote, this is pretty much useless :-)

like image 21
Gilad Barner Avatar answered Sep 22 '22 10:09

Gilad Barner