Insert a text into a textbox and simulate click on the button in Bot Framework's Web Chat

纵然是瞬间 提交于 2019-12-11 07:29:17

问题


Fiddle here: https://jsfiddle.net/chpaeeL9/1/

Microsoft Bot Framework has a webchat module that allows you to talk to your bot.

When the user clicks the Say Hi button, I want to place some text into the webchat's textbox, and click the Send button inside the webchat using JavaScript.

Sounds like something too easy, but it wasn't. Here's the code that I currently have, and it doesn't work: the click event somehow is not triggered.

$('#sayhibutton').click(function() {
  $('.wc-console').addClass('has-text'); // works
  $('.wc-shellinput').val("Hi bot!").change(); // works
  $('.wc-send').click(); // doesn't work!
  $('.wc-send svg').click(); // doesn't work either
});

Update: if that helps, it seems the interface is written using React.

Update: my question is different from my previous question about how to avoid iframes in webchat.


回答1:


OK, for the lack of a better option my solution was a pretty dirty and ugly one.

Save the code in botchat.js into a file and reference that saved file from the HTML, rather than the CDN version.

Pretty-print the file in Chrome and find the line that says:

e.prototype.sendMessage = function() {
  this.props.inputText.trim().length > 0 && this.props.sendMessage(this.props.inputText)
}

Replace the middle line with this:

this.textInput.value.trim().length > 0 && this.props.sendMessage(this.textInput.value)

This basically means to take the message text from this.textInput.value rather than from this.props.inputText, or in other words, take it directly from the textinput's DOM node.

Somehow triggering the change event on a textbox doesn't cause an actual change event on the textbox, which is why we need to do this.




回答2:


this is an issue with react try this,

var input = document.getElementsByClassName("wc-shellinput")[0];
        var lastValue = input.value;
        input.value = 'YOUR MESSAGE';
        var event = new CustomEvent('input', { bubbles: true });
        // hack React15
        event.simulated = true;
        // hack React16
        var tracker = input._valueTracker;
        if (tracker) {
            tracker.setValue(lastValue);
        }
        input.dispatchEvent(event);

        //send the message 
        $(".wc-send:first").click();

to read more see this post: https://github.com/Microsoft/BotFramework-WebChat/issues/680



来源:https://stackoverflow.com/questions/46903162/insert-a-text-into-a-textbox-and-simulate-click-on-the-button-in-bot-frameworks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!