How To Hide Command Bar Menu Item Using SPFx Extension
Recently someone posted in developer community on how to hide some menu item from command bar in Modern Experience. In this article, we will see how this can be achieved via SPFx extension application customizer.
I am assuming that you already know how to create a hello world SPFx extension, if not please go through this link.
Once you have your hello world spfx extension ready and running, let us understand how these command bar menu items are structured in HTML. For this article, we will hide a New button from this command bar.
Below is a screenshot of command bar in a typical document library, more or less it is the same for list also.
Use F12 developer console and inspect New button element, you would see something like below,
We will see that name attribute is something which is unique and can be used to identify element and apply any JavaScript code.
Let us now go to hello world extension code, open it in your editor and locate ApplicationCustomizer.ts(it would be different in your case).
Find onInit () method, add below code in this method,
@override
public onInit(): Promise<void> {
Log.info(LOG_SOURCE, `Initialized ${strings.Title}`);
let message: string = this.properties.testMessage;
if (!message) {
message = '(No properties were provided.)';
}
Dialog.alert(`Hello from ${strings.Title}:\n\n${message}`);
// code to hide button
let newbutton: any = document.getElementsByName("New")[0] || document.documentElement;
Dialog.alert(newbutton.name);
newbutton.style.display = "none";
return Promise.resolve();
}
}
If you look closely, what we are doing here is finding the New button using JavaScript and applying style with display none to hide the button.
Use ‘gulp serve’ again and preview your page(pageUrl configured in serve.json) – we can see New button is hidden.
Similarly, you can hide other menu items, use the chrome developer console to find value of name attributes.
Important points
- We can restrict this extension to a particular list/library or content type. Use custom action RegistrationType or RegistrationId to apply custom action to particular content.
- Maybe in future updates, there can be a change in name of these attributes and its values, so this needs an eye check every while and then.
- We can make this dynamic by passing parameters to extension from custom action on which all buttons need to be hidden.
- We can also use jquery and apply hierarchical based filter on elements and then apply customization.
Hope this helps … happy coding!!!
Note: This article was originally published at this link.
(Visited 215 times, 1 visits today)