Search code examples
restsalesforcegoogle-tag-managersalesforce-lightningjsforce

POST to Salesforce API using Google Tag Manager and JSforce not working?


I want to use Google Tag Manager to send data to our Salesforce org for certain events on our website (user signup, conversion etc). After some research, I realized JSforce would be the easiest way to achieve this. I created a new connected app in Salesforce, tried out the Salesforce API using Postman and successfully managed to create a new user account via the API. Then I moved on to try and achieve the same thing in Google Tag Manager. I read JSforce's docs and attempted to implement everything. But, after multiple hours of troubleshooting and Google searching, I can't seem to make it work.

Here is my current code, which is in a 'tag' in Google Tag Manager that triggers on all pages (just for testing):

https://jsforce.github.io/start/#web-browser

<script src="//cdnjs.cloudflare.com/ajax/libs/jsforce/1.9.1/jsforce.min.js"></script>
<script>
    jsforce.browser.init({
      clientId: '<MYCLIENTID>',
      redirectUri: 'https://cuttersclub.com'
    });

https://jsforce.github.io/document/#access-token

    var jsforce = require('jsforce');
    var conn = new jsforce.Connection({
      instanceUrl : 'https://um5.salesforce.com',
      accessToken : '<MYACCESSTOKEN>',
    });

https://jsforce.github.io/document/#create

    conn.sobject("Account").create({ Name : 'My Account #1' }, function(err, ret) {
      if (err || !ret.success) { return console.error(err, ret); }
      console.log("Created record id : " + ret.id);
    });
</script>

I'm getting this error in the browser console:

Uncaught ReferenceError: require is not defined

EDIT: Removing var jsforce = require('jsforce'); solved this problem and accounts are being created in Salesforce. But, now I am getting the following error in the browser console:

Access to XMLHttpRequest at '<URL>' from origin '<CALLBACKURL>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

As mentioned in the JSforce docs, I think it may be something to do with proxy servers: https://github.com/jsforce/jsforce-ajax-proxy


Solution

  • I don't know that much about salesforce, but "require" is something from node.js, not a function that is implemented in the browser.

    If I understand the documentation correctly, then for a browser project it should be enough to call the jsforce script via a script tag. You should not need any way to "require" files after that, since the jsforce script already contains everything you need. So you should be fine if you just remove the offending lines (i.e. all references to "require('jsforce');").