• This repository has been archived on 10/Jan/2024
  • Stars
    star
    315
  • Rank 132,951 (Top 3 %)
  • Language
    JavaScript
  • License
    BSD 3-Clause "New...
  • Created over 13 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

ForceTK - a minimal Force.com REST API for JavaScript apps

Force.com JavaScript REST Toolkit

This minimal toolkit allows JavaScript in web pages to call the Force.com REST API in a number of different ways.

Background

ForceTK provides a convenient, thin JavaScript abstraction of the Force.com REST API, making the API more accessible to JavaScript code running in Visualforce, in hybrid mobile apps, and elsewhere.

Due to the same origin policy, JavaScript running outside the Force.com Platform may not use XMLHttpRequest to directly invoke the REST API, so a minimal PHP proxy is provided.

Recent Updates

  • Visualforce Remote Objects are proxy objects that enable basic DML operations on sObjects directly from JavaScript. Behind the scenes, the Remote Objects controller handles sharing rules, field level security, and other data accessibility concerns. Pages that use Remote Objects are subject to all the standard Visualforce limits, but like JavaScript remoting, Remote Objects calls don’t count toward API request limits.

    Since Remote Objects are more secure than RemoteTK (which does not respect sharing rules, FLS etc since system-level access is proxied via the RemoteTK controller), and similarly do not consume API calls (the main motivation for RemoteTK), RemoteTK has been removed from the toolkit.

  • Since the Summer '13 release, the /services/data endpoint has been exposed on Visualforce hosts, so no proxy is now required for REST API calls in JavaScript served via Visualforce (although the proxy is still required for calls to /services/apexrest). forcetk.js has been updated to reflect this.

  • Inserting or updating blob data using the create or update functions (passing base64-encoded binary data in JSON) is limited by the REST API to 50 MB of text data or 37.5 MB of base64–encoded data. New functions, createBlob and updateBlob, allow creation and update of ContentVersion and Document records with binary ('blob') content with a size of up to 500 MB. Here is a minimal sample that shows how to upload a file to Chatter Files:

      <apex:page docType="html-5.0" title="File Uploader">
        <h3>
          Select a file to upload as a new Chatter File.
        </h3>
        <input type="file" id="file" onchange="upload()"/>
        <p id="message"></p>
        <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
        <script src="{!$Resource.forcetk}"></script>
        <script>
          var client = new forcetk.Client();
    
          client.setSessionToken('{!$Api.Session_ID}');
    
          function upload() {
              var file = $("#file")[0].files[0];
              client.createBlob('ContentVersion', {
                  Origin: 'H', // 'H' for Chatter File, 'C' for Content Document
                  PathOnClient: file.name
              }, file.name, 'VersionData', file, function(response){
                  console.log(response);
                  $("#message").html("Chatter File created: <a target=\"_blank\" href=\"/" + response.id + "\">Take a look!</a>");
              }, function(request, status, response){
                  $("#message").html("Error: " + status);
              });
          }
        </script>
      </apex:page>
    

    Under the covers, createBlob sends a multipart message. See the REST API doc page Insert or Update Blob Data for more details.

Dependencies

The toolkit uses jQuery. It has been tested on jQuery 1.4.4 and 1.5.2, but other versions may also work.

Configuration

ForceTK requires that you add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in Your Name > Administration Setup > Security Controls > Remote Site Settings.

Using ForceTK in a Visualforce page

Create a zip file containing app.js, forcetk.js, jquery.js, and any other static resources your project may need. Upload the zip via Your Name > App Setup > Develop > Static Resources.

Your Visualforce page will need to include jQuery and the toolkit, then create a client object, passing a session ID to the constructor. An absolutely minimal sample is:

<apex:page>
    <apex:includeScript value="{!URLFOR($Resource.static, 'jquery.js')}" />
    <apex:includeScript value="{!URLFOR($Resource.static, 'forcetk.js')}"  />
    <script type="text/javascript">
		// Get an instance of the REST API client and set the session ID
		var client = new forcetk.Client();
		client.setSessionToken('{!$Api.Session_ID}');
    
        client.query("SELECT Name FROM Account LIMIT 1", function(response){
            $('#accountname').text(response.records[0].Name);
        });
    </script>
    <p>The first account I see is <span id="accountname"></span>.</p>
</apex:page>

More fully featured samples are provided in example.page and mobile.page. Watch a brief demo of the samples.

Using the Toolkit in an HTML page outside the Force.com platform

You will need to deploy proxy.php to your server, configuring CORS support (see comments in proxy.php) if your JavaScript is to be hosted on a different server.

Your HTML page will need to include jQuery and the toolkit, then create a client object, passing a session ID to the constructor. An absolutely minimal sample using OAuth to obtain a session ID is:

<html>
  <head>

	<!-- 
	jQuery - http://docs.jquery.com/Downloading_jQuery
	-->
    <script type="text/javascript" src="static/jquery.js"></script>
	<!--
	From jQuery-swip - http://code.google.com/p/jquery-swip/source/browse/trunk/jquery.popupWindow.js 
	-->
	<script type="text/javascript" src="static/jquery.popup.js"></script>
    <script type="text/javascript" src="forcetk.js"></script>
    <script type="text/javascript">
		// OAuth Configuration
		var loginUrl    = 'https://login.salesforce.com/';
		var clientId    = 'YOUR_CLIENT_ID';
		var redirectUri = 'PATH_TO_YOUR_APP/oauthcallback.html';
		var proxyUrl    = 'PATH_TO_YOUR_APP/proxy.php?mode=native';

		var client = new forcetk.Client(clientId, loginUrl, proxyUrl);

		$(document).ready(function() {
			$('#message').popupWindow({ 
				windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri),
				windowName: 'Connect',
				centerBrowser: 1,
				height:524, 
				width:675
			});
		});

		function getAuthorizeUrl(loginUrl, clientId, redirectUri){
		    return loginUrl+'services/oauth2/authorize?display=popup'
		        +'&response_type=token&client_id='+escape(clientId)
		        +'&redirect_uri='+escape(redirectUri);
		}
	
		function sessionCallback(oauthResponse) {
		    if (typeof oauthResponse === 'undefined'
		        || typeof oauthResponse['access_token'] === 'undefined') {
		        $('#message').text('Error - unauthorized!');
		    } else {
		        client.setSessionToken(oauthResponse.access_token, null,
		            oauthResponse.instance_url);

			        client.query("SELECT Name FROM Account LIMIT 1", 
			          function(response){
			            $('#message').text('The first account I see is '
			              +response.records[0].Name);
			        });
		    }
		}
    </script>
    <p id="message">Click here.</p>
</html>

More fully featured samples are provided in example.html and mobile.html.

Using the Toolkit in a Cordova app

Your HTML page will need to include jQuery, the toolkit and Cordova. You will also need to install the InAppBrowser plugin to be able to pop up a browser window for authentication. Create a client object, passing a session ID to the constructor. You can use https://login.salesforce.com/services/oauth2/success as the redirect URI and catch the page load in InAppBrowser.

An absolutely minimal sample using OAuth to obtain a session ID is:

<!DOCTYPE html>
<html>
  <head>
    <title>ForceTK Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript" src="js/forcetk.js"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript">
		// OAuth Configuration
		var loginUrl    = 'https://login.salesforce.com/';
		var clientId    = '3MVG9Km_cBLhsuPzTtcGHsZpj9HSp.uUwbHupEXhWi6k3JJphEv8swpsUYIFCZSLp8pi7YYMbRjeQUxptYdIt';
		var redirectUri = 'https://login.salesforce.com/services/oauth2/success';

		var client = new forcetk.Client(clientId, loginUrl);

        // Make our own startsWith utility fn
        if (!String.prototype.startsWith) {
          String.prototype.startsWith = function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
          };
        }

		document.addEventListener("deviceready", function(){
            $('#login').click(function(e) {
                e.preventDefault();
                var ref = window.open(getAuthorizeUrl(loginUrl, clientId, redirectUri), 
                					  '_blank', 'location=no,toolbar=no');
                ref.addEventListener('loadstop', function(evt) {
                    if (evt.url.startsWith(redirectUri)) {
                        ref.close();
                        sessionCallback(unescape(evt.url));
                    }
                });
            });
		});

		function getAuthorizeUrl(loginUrl, clientId, redirectUri){
		    return loginUrl+'services/oauth2/authorize?display=touch'
		        +'&response_type=token&client_id='+escape(clientId)
		        +'&redirect_uri='+escape(redirectUri);
		}
	
        function sessionCallback(loc) {
            var oauthResponse = {};
            
            var fragment = loc.split("#")[1];
            
            if (fragment) {
                var nvps = fragment.split('&');
                for (var nvp in nvps) {
                    var parts = nvps[nvp].split('=');
                    oauthResponse[parts[0]] = unescape(parts[1]);
                }
            }
            
            if (typeof oauthResponse === 'undefined'
                || typeof oauthResponse['access_token'] === 'undefined') {
			    alert("Unauthorized: No OAuth response");
            } else {
                client.setSessionToken(oauthResponse.access_token, null,
			    	oauthResponse.instance_url);
                
				client.query("SELECT Name FROM Account LIMIT 1", 
					function(response){
					    $('#message').text('The first account I see is '
						+response.records[0].Name);
				    }
				);
            }
        }
    </script>
  <head>
  <body>
    <button id="login">Click here to login</button>
    <p id="message"></p>
  </body>
</html>

A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) for iOS is provided in cordova-ios.html. The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with

cordova plugin add org.apache.cordova.inappbrowser
cordova plugin add com.shazron.cordova.plugin.keychainutil

More Repositories

1

Force.com-Toolkit-for-PHP

HTML
262
star
2

LEXComponentsBundle

JavaScript
106
star
3

pub-sub-api

Sample project to get started with the Pub/Sub API
Java
105
star
4

Mobile-Design-Templates

Repo for hosting the Mobile Design Templates
JavaScript
97
star
5

open-cti-demo-adapter

JavaScript
91
star
6

LightningContainerExamples

JavaScript
67
star
7

Force.com-Toolkit-for-Ruby

Ruby
59
star
8

DataWeaveInApex

Examples for working with DataWeave scripts from Apex.
Apex
59
star
9

Force.com-Toolkit-for-Facebook

A collection of Apex classes and Visualforce pages for working with the Facebook social graph
Apex
50
star
10

SalesforceDurableStreamingDemo

Salesforce Durable Streaming Demo
Apex
41
star
11

salesforce-slack-starter-kit

Salesforce Slack Starter Kit - a minimal opinionated scaffold for building Slack Apps Integrated to Salesforce
JavaScript
39
star
12

pubsub

The c/pubsub cross DOM messaging component
JavaScript
33
star
13

LightningNowWorkshop

Workshop Content for Sales Admin Lightning Now Tour Workshop
HTML
30
star
14

troubleshoot-lwc

Base Lightning Web Components Trailhead Troubleshooting Lightning Web Components
CSS
29
star
15

elf_elk_docker

Docker image for running Salesforce Event Log File on ELK stack
Shell
25
star
16

df15-devzone-presentations

Presentations from Dreamforce 2015
24
star
17

Jetstream

streaming proxy for salesforce streaming api
Java
17
star
18

lightning-inspector-doc

Documentation for the Lightning Component Inspector, a Chrome DevTools Extension
16
star
19

MobilePack-jQueryMobile

Contains everything related to jQueryMobile MobilePack
15
star
20

pdf-generator

This project helps you generate a PDF from a Custom Compensation Object in Salesforce using Slack, Salesforce and Salesforce Functions.
JavaScript
15
star
21

lightning-out

Docs and samples for Lightning Out
JavaScript
14
star
22

reactive-salesforce-rest-angular-crud

Java
14
star
23

Force.com-Toolkit-For-Windows-Azure

C#
14
star
24

Visualforce-Charting-Examples

A few examples of all of the Visualforce Charting types as of Winter '13
Apex
14
star
25

visual-studio-tools

Microsoft Visual Studio tooling for salesforce.com
C#
13
star
26

StreamingReplayClientExtensions

Java
13
star
27

GIFter

Sample app for the Trailhead project "Quick Start: Unlocked Packages"
JavaScript
13
star
28

ExchangeRates

Apex
12
star
29

lightning-components-tutorial

Lightning Component Tutorial
HTML
11
star
30

Common-Libraries-for-NET

The Common Libraries for .NET provides functionality used by the Force.com Toolkit for .NET and the Chatter Toolkit for .NET.
C#
11
star
31

TH_CloudPages_PrefCenter

Sample HTML files for a custom preference center in Marketing Cloud.
HTML
10
star
32

MetadataDrivenTriggerHandler

Apex
10
star
33

spring-mvc-fulfillment-base

Java
9
star
34

Site.com-Quick-Start

Site.com export file to support the Site.com Quick Start
9
star
35

Force.com-Toolkit-for-Jasper

The Force.com Toolkit for Jasper is an Apex client library for the Jasper Control Center API
Apex
9
star
36

emote-server

Backend for https://github.com/fostive/emote-widget
JavaScript
9
star
37

salesforce-dx-pipeline-sample

Sample app for the hands-on bootcamp "Developing Applications with Salesforce DX and Heroku Pipelines"
Shell
9
star
38

Chatter-Toolkit-for-NET

The Chatter Toolkit for .NET provides an easy way for .NET developers to interact with the Chatter REST API using a native libraries.
C#
9
star
39

account-merge

Update accounts in a target org with data from a source org. The application uses Salesforce Functions and the pg_trgm module in Postgres to find duplicated records.
Apex
9
star
40

lightning-connect-tutorial

8
star
41

emote-widget

A widget allowing attendees to share emotion with others in real-time during a virtual event. Build with Lightning Web Components https://lwc.dev
SCSS
8
star
42

vfanalyzer

A node.js application to query Visualforce markup and related JS files for potential LEX conflicts
CSS
8
star
43

lwc-rfc-template

RFC template to design and plan LWCs
7
star
44

salesforce-slack-starter-kit-s2s

JavaScript
7
star
45

github-custom-adapter

Apex
6
star
46

PermSetUnlockedPackage

Sample repo designed for Trailhead module "Package Permission Sets Using Salesforce DX"
6
star
47

reactive-salesforce-rest-javascript-seed

Java
5
star
48

lightning-process-builder-tutorial

5
star
49

SalesforceDurablePushTopicDemo

This repository contains all the code you need to set up a Durable PushTopic Streaming client inside of a Visualforce page in your Salesforce org.
Apex
5
star
50

partner-intelligence-basics

Apex
5
star
51

MobilePack-KnockoutJS

Contains everything related to KnockoutJS MobilePack release
C
4
star
52

salesforce-canvas-seed

HTML
4
star
53

ltngx-http

A sample HTTP proxy component and JS API.
JavaScript
4
star
54

gif-booth

Add animated GIFs and Family Photo to your virtual events
JavaScript
3
star
55

Mini-hacks

Apex
3
star
56

ForcedotShell

Simple iOS WebShell app which allows you to set salesforce details via the settings app. This is really intended for demo launching rather than full-blown apps which should use OAuth for login.
Objective-C
3
star
57

SecureDevWebinar-sample

2
star
58

developerforce-Chatter-QuickPost-Firefox-Plugin

JavaScript
2
star
59

heroku-connect-status

Scala
2
star
60

use-apex-to-automate-business-processes

Trailhead Badge: Use Apex to Automate Business Processes
1
star
61

SalesforceDurableGenericDemo

Apex
1
star
62

tdx23-lwc-hack

LWC Hack for TDX23
HTML
1
star
63

soql-fields

1
star
64

demo-df13-devkeynote-s1app

Code from the DF13 Developer Keynote Salesforce1 Demo
Shell
1
star