Monday, August 23, 2010

Client Object Model Javascript and web url

Scenario:
While I found so many blog posts on how to use Client Object Model in javascript.

One thing was missing, they all had examples with hardcoded Urls. Now thats not gonna work for a real world, we need context info like web relative url.

Workaround:
I will call it a workaround until I found the perfect solution. Check the view source of any sharepoint page in SP2010. I found a javascript variable 'L_Menu_BaseUrl' which holds the web relative url.

Code:

function OpenDialog() {
var options = SP.UI.$create_DialogOptions();
options.url = L_Menu_BaseUrl + "/_layouts/xClient/MyPage.aspx";
options.width = 500;
options.height = 400;
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
Solutions:
1. Using Object model itself read the ServerRelativeUrl into a variable and use it.

<script type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(getWebProperties, "sp.js");

var relativeUrl;

function getWebProperties() {
var ctx = new SP.ClientContext.get_current();
this.web = ctx.get_web();
ctx.load(this.web, 'Title', 'Id', 'Created', 'ServerRelativeUrl');
ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFail));
}

function onSuccess(sender, args) {
relativeUrl = this.web.get_serverRelativeUrl();
}

function onFail(sender, args) {
alert('failed to get list. Error:' + args.get_message());
}

</script>
2. Using code you can output a javascript variable with Web Server Url and use it.
 this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "someData",  "<script type=\"text/javascript\">var WebRelativeUrl='" + SPContext.Current.Web.Url + "';</script>");
Articles:
SharePoint-2010-Client-Object-Model-for-JavaScript

2 comments:

Jan,  September 23, 2011 at 8:01 AM  

Hi. Nice post.

With your idea to search the javascript of a SharePoint page i came accross a global variable called _spPageContextInfo. This seems to be good solution for the problem.
I found another blog post with more information about it: http://blog.tedpattison.net/Lists/Posts/Post.aspx?ID=9

RG,  February 22, 2013 at 6:47 AM  

excellent post!
helped me a lot for a similar scenario.

Thanks!