Search code examples
javascriptnode.jsdialogflow-esmessengerfacebook-messenger-bot

how to call MessengerExtensions.requestCloseBrowser from .js file instead of an ejs file?


I am working on a chatbot in which i have used webview in node.js

I have a feedback form to be submitted by the user.

I have added messenger extensions sdk in feeback.ejs file. In the following way :

<script>
        (function(d, s, id){
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.com/en_US/messenger.Extensions.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'Messenger'));

        window.extAsyncInit = function() {
            // the Messenger Extensions JS SDK is done loading 
            var isSupported = MessengerExtensions.isInExtension(); 

            MessengerExtensions.getContext('************', 
                function success(result){

                document.getElementById("psidid").value = result.psid;
                },
                function error(result){
                //alert("json str "+JSON.stringify(result));
                }
            )

        };


    </script>

I am able to retrieve the psid as well. In the feedback form in post action I am calling a function in a js file.

eg :

<form method="post" action="/feeback/submit">

    <table cellpadding="11">

        <tr>
        <td class="label">First Name</td><td>: <input type="text" name="fname" required></td>
        </tr>
        <tr>
        <td class="label">Last Name</td><td>: <input type="text" name="lname" required></td>
        </tr>
    </table>
    </form>

In app.js file :

app.post('/feeback/submit', feedback.submit);

I am calling submit a function in feedback.js file:

In the function I am saving the form data to user and I should be able to close the webview also on successfully saving the data.

How can I acheive it?

I used the below method but I am getting MessengerExtensions is npt defined error :

MessengerExtensions.requestCloseBrowser(function success() {
    // webview closed
    user.doDataResponse(psid, message);
}, function error(err) {
  // an error occurred
});

Appreciate Help...!


Solution

  • Messenger Extensions is a client-side SDK. You can't call it from server-side code.

    On the client side you could call it when the submit event is fired, or implement your form with an XHR instead rather than form submit, then call it when you get the response back from /feeback/submit.