1

I'm trying to create a web part within SharePoint framework which includes <script> tags however they do not run while in SharePoint, see example code below:

public render(): void {
    this.domElement.innerHTML = `
    <h1>The script element</h1>

    <p id="demo"></p>

    <script>
    document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
    `;   
  }

Non working example

I know that for this example I can just us use the below to get around it.

document.getElementById("demo").innerHTML = "Hello JavaScript!";

Working example

But I have some more complicated script (calling an external JS library) which I want to use, see below:

<script id="Microsoft_Omnichannel_LCWidget" src="https://oc-cdn-ocprod.azureedge.net/livechatwidget/scripts/LiveChatBootstrapper.js" data-app-id="--My data app id--" data-lcw-version="prod" data-org-id="--My org id--" data-org-url="--My org url--"></script>

Which I don't know how to quite as easily convert into typescript for it to work. Any insight into either converting the code into typescript, or getting script tags to work is appreciated, thanks in advance.

2 Answers 2

1

If you want to use external libraries/JS in your SPFx web parts, follow steps given in below Microsoft official documentations:

  1. Use existing JavaScript libraries in SharePoint Framework client-side web parts
  2. Add an external library to your SharePoint client-side web part
0
      let myScriptTag: HTMLScriptElement = document.createElement("script");
      myScriptTag.src = myLocalScriptUrl; // like https://tenant.sharepoint.com/sites/mysite/mylib/myscript.js
      myScriptTag.type = "text/javascript";
      myScriptTag.onload = ()=>{ console.log("addJsPromise " + myLocalScriptUrl); };
      document.body.appendChild(myScriptTag);

https://bresleveloper.blogspot.com/2024/07/define-not-working-with-spfx-sharepoint.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.