Question

I've followed step-by-step this article on how to inject CSS in modern SharePoint pages using Extensions:

https://tahoeninjas.blog/2018/05/08/inject-custom-css-on-sharepoint-modern-pages-using-spfx-extensions/

Everything works perfectly in localhost but not when using CDN. The css is apparently just ignored.

This is the code that I am using in my OnInit method:

    const cssUrl: string = this.properties.cssurl;

    if (cssUrl) {
        // inject the style sheet
        const head: any = document.getElementsByTagName("head")[0] || document.documentElement;
        let customStyle: HTMLLinkElement = document.createElement("link");
        customStyle.href = cssUrl;
        customStyle.rel = "stylesheet";
        customStyle.type = "text/css";
        head.insertAdjacentElement("beforeEnd", customStyle);
    }

My goal is to inject this css to hide the left-side navigation and place the search on top of the page.

nav[role='navigation'] {
    display: none !important;
}
div[class^='searchBox_'] {
    position: absolute;
    right: 200px;
    top: 20px;
}
div[class^='pageContainer_'] {
    left: 0 !important;
}

Again, in localhost it works great. Well, not perfect because there is a delay fot the changes to occur, especially in the first access. But I can live with that.

when using --ship things don't work.

Is there an alternative way of accomplishing this?

Was it helpful?

Solution

You can use the below ready-made SPFx modern script editor web part.

Steps to deploy:

  1. Clone or Download the webpart from here

  2. Edit the Write-manifests.json.

  3. Build the package
  4. Build the package and deploy

For details steps refer to the below article :

Add The Script Editor Webpart back to SharePoint Modern Experience

OTHER TIPS

Alternative

This sample was just added to sp-dev-fx-webparts: https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/react-add-js-css-ref

It lets you add JS and CSS references on Modern Pages via SPFx application customizer extension.


For your own solution to work, make sure that all the steps under Deploying to your production tenant has been followed.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top