Creating Visualforce Pages That Work in Mobile and Desktop

Create Visualforce pages that work well in both the Salesforce1 app and the full Salesforce site by writing code that adapts to the context it’s running in.

As you learned in Managing Navigation, Salesforce1 provides a framework for handling various navigation controls and events. That framework isn’t available to Visualforce pages when they run on the full Salesforce site, because the sforce object is injected onto pages only inside Salesforce1. This means that, for pages shared between the Salesforce1 app and the full Salesforce site, you’ll want to write code that uses the sforce object when it’s available, and standard Visualforce navigation when it’s not.

For example, here is a bit of JavaScript that runs after a JavaScript remoting request successfully returns from the @RemoteAction method that creates a quick order. This code is from a Visualforce page that’s used as a custom action, which adds it to the action bar in the Salesforce1 app and the publisher menu in the full Salesforce site. It needs to work in both places. The intent of the code is to navigate to the detail page for the account for whom the order was placed:
1// Go back to the Account detail page
2if( (typeof sforce != 'undefined') && (sforce != null) ) {
3    // Salesforce1 navigation
4    sforce.one.navigateToSObject(aId);
5}
6else {
7    // Set the window's URL using a Visualforce expression
8    window.location.href = 
9        '{!URLFOR($Action.Account.View, account.Id)}';
10}

The if statement checks to see if the sforce object is available and usable. This is only true if the page is running inside Salesforce1. If sforce is available, the Salesforce1 navigation management system is used to go to the account’s detail page.

If the sforce object isn’t available, trying to use it to navigate anywhere results in a JavaScript error, and no navigation. So, instead, the code sets the window’s URL using a Visualforce expression that returns the URL for the account’s detail page. You don’t want to do this in Salesforce1 because the navigation event will be lost by the framework, but it’s required in normal Visualforce.

For more details on how to use the $Action global variable to create URLs for different kinds of objects and actions, see the Global Variables appendix in the Visualforce Developer’s Guide.