3

Currently I created an action button to my Blog Posts using SharePoint hosted solution. So when an item is created or edited, the user will be able to add content from the host web dialog back to the 'Body' field. How can we accomplish that?

Below is the code for Custom Action:

    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <!--http://sp2013.blogspot.com/2013/08/sharepoint-custom-action-xml.html-->
    <CustomAction Id="5826eb5f-1276-494b-a6a0-1ab1dd677871.SPInsertSliderAction"
            RegistrationType="List"
            RegistrationId="{$ListId:Lists/Posts;}"
            Location="CommandUI.Ribbon"
            Sequence="10001"
            Title="Insert Slider Show Link"
            HostWebDialog="TRUE"
            HostWebDialogHeight="500"
            HostWebDialogWidth="500">
<CommandUIExtension>
  <!-- 
  Update the UI definitions below with the controls and the command actions
  that you want to enable for the custom action.
  -->
  <CommandUIDefinitions>
    <CommandUIDefinition Location="Ribbon.EditingTools.CPInsert.Embed.Controls._children">
      <Button Id="Ribbon.EditingTools.CPInsert.Embed.Controls.SPInsertSliderActionButton"
              Alt="Insert Slider"
              Sequence="100"
              Command="Invoke_SPInsertSliderActionButtonRequest"
              LabelText="Insert Slider"
              TemplateAlias="o1"
              Image32by32="_layouts/15/images/placeholder32x32.png"
              Image16by16="_layouts/15/images/placeholder16x16.png" />
    </CommandUIDefinition>
  </CommandUIDefinitions>
  <CommandUIHandlers>
    <CommandUIHandler Command="Invoke_SPInsertSliderActionButtonRequest"
                      CommandAction="~appWebUrl/Pages/Default.aspx?{StandardTokens}&amp;SPListItemId={SelectedItemId}&amp;SPListId={SelectedListId}&amp;IsDlg=1"/>
  </CommandUIHandlers>
</CommandUIExtension >
    </CustomAction>
    </Elements>

In the default page I created a text field and a button, where after you click on the button it should post the message back to the body's post. How can we post the context from the app dialog back to the Body?

This is the content within the Default.aspx page

    <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
    <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
        <WebPartPages:AllowFraming ID="AllowFraming" runat="server" />

<div>
    <p>
        <label>Text</label>
        <input type="text" id="docPath" value="text here" />
    </p>

    <p>
        <button type="button" onclick="addToBodyText()">OK</button>
    </p>
</div>

    </asp:Content>

This is the code addToBodyText()

    function addToBodyText() {
        //create a link 
        var textVal = $('#docPath').val();

        //add to the body text
        //**** the below code is commented because of cross-domain issue ******//
        //var node = document.createElement("Li");                 
        //var textnode = document.createTextNode(textVal);         
        //node.appendChild(textnode);                        
        //document.getElementsByClassName("ExternalClass0E8EEF42CF1E484CA88227DC4C6BCF4B").appendChild(node);

//Close the dialog without refresh
        window.parent.postMessage('CloseCustomActionDialogNoRefresh', '*');
    }

So how can I post the message back to the Body field? I guess I can leverage that using window.parent.postMessage function but not really sure about it.

Here are the images: Custom action button Host web dialog box with text field and a button

I'm kind of stuck here!!. Any help is highly appreciated.

1

Got it! You have to make your host Body field to interact with App's IFrame

It's a matter of registering listeners on message on the Host Page so it can listen to the App's IFrame message.

Note: In this case, I've registered listeners on both App and on the Blog Post.

In [HOST]: I edited the New Post page and added the Script Editor webpart. Below is the snippet

    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
            <script type="text/javascript"> 
            (function() {

                var sendHostPageInfoListener = function (e) {

                    var messageData;

                    try
                    {
                        messageData = JSON.parse(e.data);
                        if (messageData.message != null && messageData.message !='undefined' && messageData.message !='')
                        {
                            console.log("[Host Page] Response received from App IFrame:" + messageData.message);                
                            //add response to the div body
                            $("div[id^='Body_']:last").append("<p>" + messageData.message + "</p>");                
                }
            }
            catch (error)
            {
                console.log("Could not parse the message response.");
                return;
            }

            //// Construct the return data to send to the app part
            //e.source.postMessage("hello to iFrame", e.origin);
        };

        // Register the listener
        if (typeof window.addEventListener !== 'undefined') {
            window.addEventListener('message', sendHostPageInfoListener, false);
        }
        else if (typeof window.attachEvent !== 'undefined') {
            window.attachEvent('onmessage', sendHostPageInfoListener);
        }

    })(); 

    </script>

In [SharePoint Hosted App] App.Js page:

   $(document).ready(function () {

var getHostPageInfoListener = function (e) {
    /// <summary>Callback function for getting the host page's info via postMessage api.</summary>
    console.log("[IFrame] response received from Host Page: " + e.data);

    var messageData;
    try {
        messageData = JSON.parse(e.data);
    }
    catch (error) {
        console.log("Unable to parse the response from the host page.");
        return;
    }
}

// Register the listener
if (typeof window.addEventListener !== 'undefined') {
    window.addEventListener('message', getHostPageInfoListener, false);
}
else if (typeof window.attachEvent !== 'undefined') {
    window.attachEvent('onmessage', getHostPageInfoListener);
}

    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.