Cannot access Xrm.Page.data from HTML web property in CRM 2011

I am trying to access the Xrm.Page.data object from the HTML web resource that I inserted into the form in CRM 2011. However, depending on how I try to access the Xrm object, I found that it is undefined or that Xrm.Page.data is null. The code for the web resource is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript"> function OpenMyApp(e){ alert('Xrm defined: ' + (typeof Xrm != 'undefined')); // The line above returns the string 'Xrm defined: false' alert('window.top.opener.parent.Xrm defined: ' + (typeof window.top.opener.parent.Xrm != 'undefined')); // The line above returns the string 'window.top.opener.parent.Xrm defined: true' alert('frames[0].Xrm defined: ' + (typeof frames[0].Xrm != 'undefined')); // the line above will actually throw an error and stop the script, because the frames collection is empty. alert(window.top.opener.parent.Xrm.Page.data); // the line above returns null. // var myId = Xrm.Page.data.entity.attributes.get("new_field_i_want").getValue(); // The line above is what I would like to see work. e.preventDefault(); } </script> </head> <body> <a onClick="OpenMyApp(event);" href="#">My Link</a> </body> </html> 

I successfully got Xrm.Page.data from a JavaScript function that is part of a library that fires a form event (e.g. Form.Load). It is simple when it is embedded in the HTML web resource in the form that I am facing this problem. Can someone explain what I'm doing wrong, and if there is a way to access Xrm.Page.data in this way, what would I like to do?

Thanks.

+6
source share
3 answers

Try accessing Xrm using the following syntax:

 window.parent.Xrm.Page.getAttribute()... window.parent.Xrm.Page.getControl()... window.parent.Xrm.Page.context... 

as

 alert(window.parent.Xrm.Page.data.entity.attributes.get("new_field_i_want").getValue()); 

From your sample code.

+13
source

This works when you have a web resource loaded in an iframe / dialog. It gains access to the parent frame, then searches for all available frames and checks which frame has

Xrm.Page.data! = Null

code...

 $.each(parent.window.frames, function(i,val){ if (parent.window.frames[i].Xrm.Page.data != null) { parent.window.frames[i].Xrm.Page.data.entity.attributes.get('ownerid').setValue([{ id: '{' + sourceKey + '}', name: name, entityType: "systemuser" }]); parent.window.frames[i].Xrm.Page.data.entity.save(); break; } }); 
+2
source

Based on TWilly's answer, I created a function below to get an Xrm object

 GetXrm: function () { var frame = $.grep(parent.window.frames, function (e) { if (e.Xrm.Page.data) return true; }); return frame[0].Xrm; } 
+1
source

All Articles