A while back, I had two posts concerning the execution of Fetch against the 2011 service (1 & 2). A couple days ago, I received some great comments concerning these posts. One of the comments highlighted a frequent stumbling block I have seen with CRM 2011 – JavaScript Execution Context. Mainly, I’m talking about the JavaScript variable “Xrm”. I think we all got a little spoiled with “crmForm.all”; however, after you get acquainted to using “Xrm”, I think you’ll feel “crmForm.all” was a little bloated. (With it being summer, “Xrm” is ready for the beach!)
In these examples, I’m going to demonstrate executing the getServerUrl() method from an entity’s form.
Inside of a JavaScript Web Resource
To access the getServerUrl() method, simply use:
Xrm.Page.context.getServerUrl()
Inside of an embedded HTML Web Resource (aka an IFrame)
Now since we’re talking context, you can always reference the “ClientGlobalContext.js.aspx” and use:
GetGlobalContext().getServerUrl()
But I’m wanting more than what’s inside Xrm.Page.context; I want everything inside the “Xrm” variable. For this we can use:
window.parent.Xrm.Page.context.getServerUrl()
To use the “window.parent.Xrm”, you will need to make sure Cross-Scripting is enabled.
Inside of Developer Tools (F12)
I’ve seen people use crmForm.all and then use the CRM 4 to CRM 2011 conversion utility to code. Instead, it’s much easier to use:
document.getElementById('contentIFrame').contentWindow.Xrm.Page.context.getServerUrl()
Summary
If you aren’t familiar with Execution Context, I would recommend delving a little deeper. My intentions for this was merely to demonstrate how to use the “Xrm” variable in the different scenarios. So whether you are using the Console inside Developer Tools or whatever, you can see using the “Xrm” variable is easy once you have the right execution context.
One quick tip, is that if you've got the Developer Tools open, a handy shortcut to the Xrm object is:
frames[0].Xrm.Page...
Saves a lot of typing. However to be safe, if you're trying to access Xrm.Page from code you're actually going to end up publishing ... I'd definitely stick with the method you listed already.
Posted by: William Dibbern | July 24, 2011 at 05:01 PM