简体   繁体   中英

React Typescript, Call a function from external script

In my react application, I fetch a custom javascript file from the server and append it as a script tag to the body of document .

this newly added custom file contains a method called manipulator . Now in one of the components, I want to call that function. As I know the function should exist in the window global object.

if(documnet.getElementById('customJsId')){ // check if the script tag exists in document
 window.manipulator(); // which I get Property 'iframeManipulator' does not exist on type 'Window'.ts(2339)
}

But here I get the compiler error

Property 'manipulator' does not exist on type 'Window'.ts(2339)

which is totally logical, but I did not find a way to create an extended interface for window or any other way to tell the compiler that there is an optional function in window called manipulator .

Any help is appreciated.

  ----------Just in case--how the script is added to document--------------
  loadProjectCustomJS() {
    runInAction(async () => {
      thisfetchProjectJs().then((doc) => {
        const body: HTMLBodyElement = document.getElementsByTagName('body')[0];
        const customjs: HTMLScriptElement = document.createElement('script');
        customjs.type = 'text/javascript';
        customjs.id = 'customJsId'
        customjs.src = doc.get('resourceUrl');
        body.appendChild(customjs);
      });
    });
  }

You can add it to the Window interface from inside a TypeScript module (ts or tsx) like this:

declare global {
  interface Window {
    manipulator: () => void;
  }
}

Or you can create a global global.d.ts (name doesn't matter, only that it's inside your source directory), containing this:

declare interface Window {
  manipulator: () => void;
}

Be aware that this makes the function available everywhere, also before the script is initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM