Pages

1/31/2010

SharePoint: Using JavaScript in a Feature CustomAction

 

You can add to most of SharePoint’s menus by creating a Feature to define a CustomAction. When using CustomAction you need to supply a <UrlAction> element with the URL of the page to redirect to. When you replace the URL with JavaScript some weird things happen:

 

If you have:
    <UrlAction Url="javascript:alert('hello')"/>
SharePoint renders it as:
    onMenuClick="window.location = 'javascript:alert(\'hello\')';"
This works just fine as Alert returns null.

If you have JavaScript that sets a value (=) then the JavaScript returns the result and the <A> tries to redirect to that result:  (This example sets the URL to an <IFRAME> to a page in LAYOUTS)
    <UrlAction Url="javascript:document.getElementById('getthetime').src
                                       = 'http://yoursite/_layouts/CurrentTime.aspx'"/>
SharePoint again renders it as "window.location=" and clicking the link redirects to a blank page with the SRC value displayed.

 

The trick it to make sure your JavaScript code returns NULL, so wrap your code in VOID()
      <UrlAction Url="javascript:void(document.getElementById('getthetime').src
                                       = 'http://yoursite/_layouts/CurrentTime.aspx')"/>
The JavaScript now runs and there is no page redirect.

 

In general:

       <UrlAction Url="javascript:void(your javascript code)"/>

 

 

Here’s an example feature:

Assuming that you have a page in LAYOUTS named CurrentTime.aspx you want to load into an <IFRAME> with an ID of “getthetime)…

feature.xml file:

<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="9fa44e31-b703-4094-ad7c-2f3d9eac6f64"
          Title="MenuWithJS"
          Description="Demo of using JavaScript in a Custom Action"
          Version="1.0.0.0"
          Hidden="FALSE"
          Scope="Web"
          xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>    
  </ElementManifests>
</Feature>

 

elements.xml file: (this example adds the new menu choice to the Site Actions menu)

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!-- Add the action to the Site Actions Menu Dropdown -->
  <CustomAction Id="JSdemo"
    GroupId="SiteActions"
    Location="Microsoft.SharePoint.StandardMenu"
    Sequence="1000"
    Title="JavaScript Test">
    <UrlAction Url="javascript:void(document.getElementById('getthetime').src = 'http://maxsp2007/sites/training/_layouts/CurrentTime.aspx')"/>
  </CustomAction>
</Elements>

 

 

Note: only tested in Internet Explorer…

1 comment:

JavascriptBank.com said...

very cool & good tip, thank you very much for sharing.

Post a Comment

Note to spammers...
Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.