Search code examples
javascriptsharepointsharepoint-2013sharepoint-clientobject

How to use the javascript getPeerUrl() function in Sharepoint 2013 client object model?


I want to use this function https://msdn.microsoft.com/en-us/library/office/jj954403.aspx to get the french url from the english url (I can't just simply change the en to fr and vice versa).

But I am having trouble with the function. It seems to give me 0 instead of the actual url.

This is my code

function VariationHandler2() {


    var ctx = SP.ClientContext.get_current();
    var site = ctx.get_site();
    var rootWeb = site.get_rootWeb();
    var webProperties = rootWeb.get_allProperties();

    ctx.load(site);
    ctx.load(rootWeb);
    ctx.load(webProperties);
    ctx.executeQueryAsync(

        function() {
            var varLabelsListId = webProperties.get_item('_VarLabelsListId');

            var labelsList = rootWeb.get_lists().getById(varLabelsListId);
            var labelItems = labelsList.getItems(SP.CamlQuery.createAllItemsQuery());

            ctx.load(labelItems);
            ctx.executeQueryAsync(

                function() {
                    var url = rootWeb.get_serverRelativeUrl();

                    var object = SP.Publishing.Variations.getPeerUrl(ctx, "/en/Pages/default.aspx", "fr");
                    alert(object);
                    alert(object.get_value());
                    alert(JSON.stringify(object));

                },
                function() {
                }
            );
        },
        function() {
        }
    );  
}

but I am not getting any useful results. Does anyone know how to get it to work?

Thanks


Solution

  • I added the following code to a Content Editor on a publishing page in a site with variations and it worked:

    <script src="/_layouts/15/sp.publishing.js" type="text/javascript"></script> 
    <script type="text/javascript">
    $(document).ready(function() {
        ExecuteOrDelayUntilScriptLoaded(VariationHandler, "sp.js"); 
    });
    
    function VariationHandler() {
        ExecuteOrDelayUntilScriptLoaded(VariationHandler2, "SP.publishing.js"); 
    }
    
    
    function VariationHandler2() {
            var ctx = SP.ClientContext.get_current();
            var object = SP.Publishing.Variations.getPeerUrl(ctx, "/en/Pages/default.aspx", "fr");
            ctx.executeQueryAsync(
    
                function() {
                    alert(object.get_value());
                }
            );  
        }
    </script>