Get the Selected WebPart ID with Client-Side code (JavaScript)

This week one of my coworker needed to retrieve the Storage ID of the selected WebPart in the page. Since he needs to do that from a Custom Action in the Ribbon, he has to use JavaScript code to retrieve the ID.

The solution came to me when looking into the definition of the SP.ListOperation.Selected.getSelectedItems function. If this function is able to get the selected Items of a ListView WebPart, it probably knows how to retrieve the selected WebPart and maybe its ID. This function calls the GetSelectedItemsNative function which is defined into CORE.js. Inside its body the GetCurrentCtx function is called. Here is its definition :

Yeah! That’s exactly what we need. The purpose of this function is to retrieve the context of a ListView WebPart (List URL, Web URL etc…) but the main part of the code is about retrieving the ID of the WebPart. Let’s rewrite it :

If you don’t know how to retrieve your WebPart server-side with this ID, check this code :

I hope it will help you Vincent 😉