submit a comment on Instagram posts using jQuery o

2020-07-26 14:40发布

问题:

I need to submit a comment on an Instagram post, using javascript or jQuery, so I use :

$('input[placeholder="Add a comment…"]').val('MY COMMENT');

This code fills the comment textbox for and instagram post page like this :

And the last thing which I need is triggering of "Enter" button. I've tried codes below that I'd found on stackoverflow but no luck :

1)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyboardEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

2) to be sure about the selector, I changed text color to red, and the selector has been selected correctly.

$('input[placeholder="Add a comment…"]').val('MY COMMENT');
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("input").first().css('color','red').trigger(e);

I think this kind of triggering the "Enter" key is not suitable, is there any other way to trigger "Enter" key just like as it is pressed on the keyboard?

Any help would be appreciated.

回答1:

I found a solution but that is not as @SalmanShariati wrote in his comment.

Instead of triggering a KeyBoardEvent on the textarea trigger a submit event on the parent form.

var form = document.querySelector("form"); // that is the only form on the page
form.dispatchEvent(new Event("submit")); // make sure to change the value of the textarea to your required comment before doing this

This worked for me.