Sometimes, we need to send the data from one web part to another web part for filtering/display. In SSOM, we do have connected web parts using interface. But in Apps, we don't have something by default. We need to use postMessage and event listeners to achieve the same.
I have a client add-in (Sender), where users fill the form like Name, Age, Company etc. and on clicking the Submit button, we have to show the data in another client add-in (Receiver).
Create a SharePoint Hosted App.
Creating Sender Web part, add a Client Web part and name it as Sender.
Which will add a Web part, Element.xml, and an ASPX page.
Add all HTML elements for collecting the data.
Create a JavaScript file (name it Sender.js) and paste the below code and add reference to the Sender.aspx page in it. We have to capture the details entered by a user into the object and send to the host web using postMessage.
- $(document).ready(function () {
- $("#Send").on('click', function () {
- var appMsg = {
- metadata:"AppSender",
- Name: $("#Name").val(),
- Age: $("#Age").val(),
- Company: $("#Company").val()
- };
- window.parent.postMessage(appMsg, "*");
- })
- });
Deploy the Solution and add two web parts onsite page inside your Hosted Web
On the same page, add script editor webpart and add the below code. We are adding event listener to the host web window and capturing the data sent by sender webpart and checking the metadata property (custom property created in the object). If matched, then it is sending message to the receiver app by using iframe postMessage.
- <script src="/sites/DeveloperSite/SiteAssets/scripts/jquery-1.9.1.min.js"></script>
- <script>
- $(document).ready(function() {
- window.addEventListener("message", receiveMessage, false);
-
- function receiveMessage(event) {
- var receivedData = event.data;
-
- if (receivedData.metadata && receivedData.metadata == "AppSender") {
- procesHello(receivedData);
- }
- }
-
- function procesHello(msgData) {
-
- var iFrame = document.getElementsByTagName("iframe")[1];
- iFrame.contentWindow.postMessage(msgData, "*");
- }
- });
- </script>