Compartilhar via


Use JavaScript with Microsoft Dynamics CRM 2013

 

Applies To: Dynamics CRM 2013

Microsoft Dynamics CRM 2013 and Microsoft Dynamics CRM Online provide many opportunities to use JavaScript. All JavaScript used in Microsoft Dynamics CRM is added by creating JScript web resources. This topic has information for developers who use JavaScript and includes links to relevant topics in the Microsoft Dynamics CRM SDK and other sources.

In This Topic

Areas where you can use JavaScript in Microsoft Dynamics CRM

Use of jQuery

Write JavaScript for multiple browsers

Data access using JavaScript

JavaScript programming best practices

Debugging JavaScript in Microsoft Dynamics CRM

Areas where you can use JavaScript in Microsoft Dynamics CRM

You can use JavaScript to perform actions in form scripts, command bar (ribbon) commands, and web resources.

Form scripts

The most common use of JavaScript in Microsoft Dynamics CRM is to add functions as event handlers for entity form events. For more information, see Write code for Microsoft Dynamics CRM 2013 forms.

Command bar (ribbon) commands

When you customize the Microsoft Dynamics CRM command bar, you can configure commands for controls that you add. These commands contain rules that control whether the control is enabled and what action is performed when the control is used. For more information, see Customize commands and the ribbon.

Web resources

Microsoft Dynamics CRM provides an organization-owned entity that stores a binary representation of a file that can be accessed by using a URL. This file is called a web resource. There are several types of web resources. A web resource that represents a JavaScript library is called a JScript web resource. You can use a webpage (HTML) web resource to provide a user interface with JavaScript libraries included just as you would for files on a web server. Because these files are part of Microsoft Dynamics CRM, users who access them are already authenticated. Therefore, you can use Microsoft Dynamics CRM web services without having to write code to authenticate the user. For more information, see Web resources for Microsoft Dynamics CRM 2013.

Use of jQuery

  • Use jQuery with HTML web resources
    We recommend that you use jQuery together with HTML web resources to provide user interfaces because it is an excellent cross-browser library.

    With HTML web resources, you control the libraries that are present and there is no restriction against manipulating the DOM. Feel free to use jQuery within your HTML Web resources.

  • Avoid using jQuery with form scripts or ribbon commands
    We do not recommend using jQuery in form scripts and ribbon commands.

    Most of the benefit provided by jQuery is that it allows for easy cross-browser manipulation of the DOM. This is explicitly unsupported within form scripts and ribbon commands. Restrict your scripts to use the Xrm.Page and Xrm.Utility libraries available in form scripts and ribbon commands. If you decide to use the remaining capabilities of jQuery that are useful with Microsoft Dynamics CRM and include the ability to use $.ajax, consider the following:

Write JavaScript for multiple browsers

Because you don’t know what browser will be in use, you should make sure that any scripts that you use will work with all supported browsers. Most of the significant differences between Internet Explorer and other browser have to do with HTML and XML DOM manipulation. Because HTML DOM manipulation is not supported, if script logic is only performing supported actions and using the Xrm.Page API the changes required to support other browsers could be small. Use the Custom Code Validation Tool to identify code that only works for Internet Explorer.

A cross-browser library like jQuery is a good solution for developing web resources but should not be necessary for form scripts or ribbon commands. More information: Use of jQuery

Support for other browsers

Because Microsoft Dynamics CRM 2013 and Microsoft Dynamics CRM Online supports W3C standards, the application will be accessible using any modern browser and from any platform that supports those standards. However Microsoft Dynamics CRM will only be tested using a specific set of browsers and platforms. For the list of supported platforms and browsers see Supported web browsers.

If you use a browser, or browser version, that is not supported and you type just the server name or server name with organization as the URL, you will be redirected to the Microsoft Dynamics CRM for phones page. The CRM for phones pages can be expected to work properly on most browsers, such as browsers used in mobile devices, with limited functionality.

Control browser support for your organization or solution

Although creating public websites requires that you support most modern browsers, few public websites support all browsers that have ever existed. You need to establish what browsers you will support. To save development and testing costs, many business applications require that users use specific browsers.

If you are an ISV preparing solutions for any organization using Microsoft Dynamics CRM, you should expect that any organization could use one of the browsers that Microsoft Dynamics CRM 2013 and Microsoft Dynamics CRM Online will support. However, if you are preparing customizations only for an organization that requires that people use a specific browser, there is no reason to develop and test your customizations for browsers the organization doesn’t support.

Network administrators may use Software Restriction Policies and/or AppLocker to enforce which applications are allowed to run or be installed on a domain.

Technical Article: Control Which Browsers Your Organization Supports provides an approach that a developer can modify to enforce browser policy options for just the Microsoft Dynamics CRM application.

XMLHttpRequest status values

Internet Explorer sometimes uses a different XMLHttpRequest status value that is used in onreadystatechange event handlers. When applying an UPDATE or DELETE action, Internet Explorer may return a status value of 1223 rather than the expected value of 204. To compensate for this, you should check for both as shown in the following code sample:

if (this.readyState == 4 /* complete */) {
    this.onreadystatechange = null; //avoids memory leaks
    if (this.status == 204 || this.status == 1223) {
     //Success
    }
    else {
     //Error
    }
   }

The SDK.REST.js library and other libraries in the SDK samples check for both possible status values using this technique. For more information about these libraries, see Sample: Create, retrieve, update, and delete using the OData endpoint with JavaScript and Sample: Retrieve entity metadata using JavaScript.

Parsing XML

There are many opportunities where you will need to parse XML using JavaScript. Be aware that there are significant differences in the way you can parse XML using Internet Explorer and other browsers. Internet Explorer uses Microsoft XML Core Services (MSXML) APIs to interact with XML document objects. These APIs include a number of extensions to the W3C DOM that are not available to other browsers. Following are two examples:

  • Two common methods used to extract data from an XML document using Internet Explorer are selectNodes and selectSingleNode. Both of these methods use an XPath expression as the parameter and return either a node or a node list. For other browsers, use the evaluate method when you want to use an XPath expression. Alternatively, you can refactor your code to navigate the document hierarchy and use the getElementsByTagNameNS method.

  • Internet Explorer uses the text property to access the text of an element. Other browsers use the textContent property.

There are a number of different ways you can address these differences. The approach you use depends on your preferences and the requirements of your code.

The SDK.MetaData.js library found in Sample: Retrieve entity metadata using JavaScript uses helper functions. This library uses the SOAP endpoint for web resources to retrieve entity and attribute metadata. This library depends on parsing data from the XML document returned as XMLHttpRequest.responseXML. In this library the following helper functions were added and used throughout the other functions in the library.

With these helper functions the existing code that was written only for Internet Explorer was updated as shown:

Original Internet Explorer Only Code

New Function to Support Multiple Browsers

node.selectNodes(XPathExpr);

SDK.MetaData._selectNodes(node,XpathExpr);

node.selectSingleNode(XPathExpr);

SDK.MetaData._selectSingleNode(node, XPathExpr);

node.selectSingleNode(ElementName).text;

SDK.MetaData._selectSingleNodeText(node, ElementName);

node.text

SDK.MetaData._getNodeText(node);

Data access using JavaScript

There are two web services you can use within the application to access data by using JavaScript.

OData (REST) endpoint

Previously known as the ‘REST endpoint for web resources’. You can use the OData endpoint to execute HTTP requests by using a web service that is based on a Uniform Resource Identifier (URI). “RESTful” web services are popular because they can make programming easier.

The current implementation of the OData endpoint is limited to create, retrieve, update and delete operations. The Sample: Create, retrieve, update, and delete using the OData endpoint with JavaScript includes an SDK.REST.js library that provides an example of a reusable library that can further simplify using the OData endpoint.

One of the advantages of the OData endpoint is that it implements the OData protocol, which provides the way to query and update data. When you use JavaScript, you usually retrieve objects in JavaScript Object Notation (JSON) format. This makes the results easier to work with. The primary limitation of the OData endpoint is that you cannot use the IOrganizationService.Execute method to execute messages (Request and Response classes). You use the SOAP endpoint for web resources to execute messages.

For more information, see Use the OData endpoint with web resources.

SOAP endpoint

The SOAP endpoint lets you execute messages because the REST endpoint does not yet allow this. You can also call the Create, Retrieve, Update, Delete and RetrieveMultiple methods of this web service, but using it is not as easy as using the REST endpoint.

Microsoft Dynamics CRM does not provide a JavaScript library to facilitate using the SOAP endpoint. When using the SOAP endpoint, you must post http requests that contain the XML defining the request and then parse the XML returned in the response.

The SDK provides a Microsoft Visual C# solution called SoapLogger that lets you capture the XML sent and received when you perform operations with the Microsoft Dynamics CRM web services by using Visual C#. With this information, you can build your own JavaScript libraries. Microsoft CRM MVP Jamie Miley has released a CRM 2011 Jscript Soap Request Formatter program on CodePlex that takes this a step further and actually generates JavaScript libraries for you.

The SDK includes an example that shows how to retrieve entity and attribute metadata. For more information, see Sample: Retrieve entity metadata using JavaScript. The SDK.MetaData.js library in that sample can be used when you want to retrieve entity or attribute metadata.

For more information, see Use the Modern app SOAP endpoint for modern applications with web resources.

JavaScript programming best practices

The following sections describe best practices when you use JavaScript with Microsoft Dynamics CRM.

Avoid using unsupported methods

On the Internet, you can find many examples or suggestions that describe using unsupported methods. These may include leveraging undocumented internal function for page controls. These methods may work but because they are not supported you can’t expect that they will continue to work in future versions of Microsoft Dynamics CRM.

Use the Custom Code Validation Tool to identify code that is using unsupported methods.

Use a cross-browser JavaScript library for HTML web resource user interfaces

A cross-browser JavaScript library, such as jQuery, provides many advantages when developing HTML web resources that must support multiple browsers. JavaScript libraries like jQuery provide a unified development experience for all browsers supported by Microsoft Dynamics CRM. These capabilities are appropriate when you are using HTML web resources to provide user interfaces. JavaScript libraries like jQuery provide consistent ways to interact with the Document Object Model (DOM).

Do not use jQuery for form script or commands

We do not recommend or support using jQuery for any pages within the application. This includes form scripts and ribbon commands. More information: Use of jQuery.

Recognize limitations for content delivery network (CDN) libraries

Content delivery network (CDN) JavaScript libraries provide many advantages for public websites. Because these libraries are hosted on the Internet, you do not need to create web resources that contain the content of the libraries. For Microsoft Dynamics CRM you should consider the following issues before you use a CDN JavaScript library.

  • Users of the Microsoft Dynamics CRM for Microsoft Office Outlook with Offline Access client have the capability to work with no Internet connection while working offline. If you are depending on an Internet connection for your JavaScript libraries, your code will fail.

  • Some organizations will restrict Internet access for employees. Unless they configure the network to allow access to the CDN library sites, your code may fail for those organizations.

The alternative to using CDN libraries is to create a script (JavaScript) web resource with the contents of the library. Because web resources are organization-owned entities they will be synchronized when a Microsoft Dynamics CRM for Outlook with Offline Access user goes offline. Because these web resources now become part of the application they will not be blocked if an organization restricts access to the Internet.

Use feature detection when writing functions for multiple browsers

Even when you use a cross-browser library like jQuery, you need to be very aware of differences between browsers. You can generally detect which browser is being used by querying the navigator.useragent property. This is called browser detection. Browser detection is not a good strategy for most cases because it can’t take into account what features newer versions of a browser have. Also, some browsers provide the capability to modify the navigation.useragent property so that they appear to be a different browser.

Feature detection is the recommended approach. By detecting what features are available, you can create code paths for the browsers you support without knowing exactly which browser is being used. For more information about feature detection, see How to Detect Features Instead of Browsers.

Do not access the DOM

JavaScript developers are used to interacting with Document Object Model (DOM) elements in code. You might use the window.getElementById method or the jQuery library. You are free to use these techniques in your HTML web resources, but they are not supported to access elements in Microsoft Dynamics CRM application pages or entity forms. Instead, access to entity form elements are exposed through the Xrm.Page object model. The Microsoft Dynamics CRM development team reserves the right to change how pages are composed, including the ID values for elements, so using the Xrm.Page object model protects your code from changes in how pages are implemented. For more information, see Use the Xrm.Page object model.

Define unique names for your JavaScript functions

When you are the only developer for an HTML page you can easily manage the names of the JavaScript functions you use. In Microsoft Dynamics CRM, other solutions may add JavaScript functions to the page where your function is used.

If two JavaScript functions on a page have the same name, the first function defined is overwritten by the second. For this reason, make sure that you define unique names for your JavaScript functions. For more information, see Creating script libraries.

Use asynchronous data access methods

When you access data by using the Microsoft Dynamics CRM web services that use the REST or SOAP endpoint for web resources, always use an XMLHttpRequest that is configured to execute asynchronously. The reason is that the browser operates on a single thread. If that thread is being used to execute a long-running process synchronously the browser will stop responding.

Debugging JavaScript in Microsoft Dynamics CRM

Each browser provides some kind of debugging extension. Internet Explorer provides developer tools you can use to debug scripts in Microsoft Dynamics CRM. The Internet Explorer developer tools can be opened by pressing F12 when viewing a page using Internet Explorer. For more information, see How-to series: Easily debug your CRM JavaScript code in IE8 and Debugging Script with Developer Tools.

For Google Chrome, press F12 to open developer tools. Firebug is a popular browser extension for web development using Mozilla Firefox. For Apple Safari, you must first choose the Show Develop menu in menu bar in Advanced Preferences. Then you can choose Show Web Inspector from the Develop menu.

You can also use Microsoft Visual Studio. For more information, see How to Debug JScript in Microsoft Dynamics CRM 2011.

When you use JavaScript libraries in Microsoft Dynamics CRM, your libraries are added to a page that includes many libraries. It can sometimes be difficult to isolate your specific library in the debugging environment. When using debugging tools in Internet Explorer, on the Script tab, expand the available scripts and find the one with the name that corresponds to the name of your JavaScript web resource, such as the new_debugging_example_script.js web resource shown below.

Debugging JavaScript

Debugging tools for different browsers have similar capabilities. Once you have found your library, you can set a break point and recreate the event that should cause your code to run.

Write messages to the console

Using the window.alert method when debugging JavaScript is still a common way to troubleshoot code in the application. But now that all modern browsers provide easy access to debugging tools, it is not a best practice, especially when others might be using the application you are debugging.

Consider writing your messages to the console instead. The following is a small function you can add to your libraries that you can use to send any messages you want to view to the console when it is open.

function writeToConsole(message)
{
 if (typeof console != 'undefined') {
  console.log(message);
 }
}

Unlike using the alert method, if you forget to remove any code that uses this function, people using the application will not see your messages.

See Also

Write client application extensions
Use web service data in web resources (OData and Modern app SOAP endpoint)
Write applications and server extensions
Write code for Microsoft Dynamics CRM 2013 forms
Customize commands and the ribbon
Web resources for Microsoft Dynamics CRM 2013
Use the OData endpoint with web resources
Use the Modern app SOAP endpoint for modern applications with web resources
Use the Xrm.Page object model