Passing data from a CRM form to HTML web resource is quite a common scenario. If the requirement is to send few values like GUID or some text, then we can send it using Data attribute through URL.

But what if we have to send huge data (which is beyond the maximum length allowed to send in URL), or if we have to return huge data from HTML web resource to CRM form?

Let’s look at the following scenario which we had in a recent project.

We have an entity called “Notification” which captures the information related to a notification. And the notification has a 1:N relationship with Contact entity so that each notification would be linked with one or more contacts. Now the tricky part is the customer wants to first select the contacts (using some complex filter criteria) and then to fill other details of the notification on the form. This is not the usual flow as in CRM, first we need to create the record (notification), and then we can add the contacts using the subgrid. I cannot use OOB Advanced Find window as I cannot select more than 250 contacts from the Advanced Find result page.

Then we decided to use a HTML web resource so that the user who searches for contacts has more control on the list of contacts (like adding/removing the contacts from the search results). But then the challenge with this approach is to send back the selected contacts in HTML page to the Notification form in CRM.

To solve the purpose, we can make use of the window.postMessage()  to communicate between the scripts on different pages.

Window.postMessage()  can be used to send messages between two windows/frames within same origin or cross-origin.

Let’s see how to use this.

In the sender window script:

The window that wants to send a message calls postMessage method of the receiving window.

Use Window.PostMessage(data, targetOrigin); 

Here…

Window – is the object to which we are sending the message.

data – object which contains the message to be sent

targetOrigin – specifies the origin for the target window so that only a window from the given origin will get the message. Use “*” if we don’t want to check for the origins.

In the receiver window script:

Use window.addEventListener()  to receive the message.

In HTML page script:

Using the above methods, in the custom HTML page, I have allowed the user to select the contacts  and the selected contacts GUIDs have been sent to the Notification Form script in CRM using window.opener.postMessage(contactGUIDsString , "*");

In the Notification.js file in CRM:

Using the window.addEventLsitener() , received the GUIDs sent from HTML web resource and stored them in an object which can be later used to associate the contacts with the saved notification.

This method can also be used to communicate between an Iframe and CRM form.

I have tested this method working successfully in IE 11 and Chrome 60.0.3112.101.