[SalesForce] How to use “jsforce” in an external HTML client for streaming api

I am trying to use streaming API feature of salesforce, and be able to subscribe to the topic in an external client which is HTML based.

My code is below:

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jsforce/1.9.1/jsforce-core.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jsforce/1.9.1/jsforce-api-streaming.min.js"></script>

        <script>
        function myFunction() {
        var jsforce = require('jsforce');
        var username = 'XXXXX';
        var password = 'YYYYY';
        var securityToken = 'ZZZZZ';
        const conn = new jsforce.Connection({loginUrl : 'https://test.salesforce.com'});
        conn.login(username, password + securityToken, function(err, res) {
          if (err) { 
              return console.error(err);
          }
        console.log('Authenticated');

        conn.streaming.topic("PushTopicUpdates").subscribe(function(message) {
            console.log('Event Type : ' + message.event.type);
            console.log('Event Created : ' + message.event.createdDate);
            console.log('Object Id : ' + message.sobject.Id);
            console.log('Event : ' + JSON.stringify(message));
          });
        });
        }
        </script>
    </head>
    <body onload="myFunction()">
    </body>
</html>

I am getting an error as below:

Uncaught ReferenceError: require is not defined
at myFunction (StreamingAPI.html:8)
at onload (StreamingAPI.html:31)

Best Answer

This is a more general programming question, but since this is a Salesforce library I think an answer fits on our site.

The require() function that you're calling is typically provided by a web build tool or requirejs. By using the latter as well you should then be able to use it as you're trying to here.

The JSForce site itself has instructions on how to use it in a web page context though, and you'll likely find this to be the easier option for you:

<script>
    jsforce.browser.init({
        clientId: '[ your Salesforce OAuth2 ClientID is here ]',
        redirectUri: '[ your Salesforce registered redirect URI is here ]'
    });

    jsforce.browser.on('connect', function(conn) {
        conn.streaming.topic("CommandCenterUpdates").subscribe(function(message) {
        // etc.
Related Topic