在脚本标签上调用JS函数

时间:2020-08-21 18:54:56

标签: javascript reactjs

我正在尝试将Trulioo实施到React应用程序。他们的文档要求在页面上放置一个<script>标签,这将呈现其申请表:

<div id="trulioo-embedid"></div>

<!-- This script renders the form for the div above --> 
<script type="text/javascript" src="https://js.trulioo.com/latest/main.js"></script>

<!-- Initialize your form here with your Frontend (FE) key -->
<script> 
  // Handle the response of EmbedID after form submits
  function handleResponse(e) { 
    console.log('handleResponse', e); 
  } 
  
  const publicKey = 'Trial Key (FE)_OR_Live Key (FE)'; // Public Key
  // const accessTokenURL = 'http://localhost:8080/trulioo-api/embedids/tokens';
  new TruliooClient({ 
    publicKey, 
    // accessTokenURL,
    handleResponse 
  });
</script>

我以React方式实现了它

import React, { useEffect } from 'react';
import truliooConfig from '../../../config/tuliooConfig';

export default function CustomerSignup() {
    function handleResponse(e) {
        console.log(e);
    }
    const { publicKey, accessTokenURL } = truliooConfig;

    useEffect(() => {
        const script = document.createElement('script');
        script.src = 'https://js.trulioo.com/latest/main.js';
        script.async = true;

        document.body.appendChild(script);

        /*new TruliooClient({
            publicKey,
            accessTokenURL,
            handleResponse,
        });*/

        return () => {
            document.body.removeChild(script);
        };
    }, []);

    return <div id="trulioo-embedid" />;
}

该脚本可以很好地加载,并且已附加到DOM,但是我需要使用身份验证参数调用new TruliooClient({})

我不确定如何调用它,因为它没有在React中定义。

我该如何解决这个问题?

预先感谢

编辑:添加

script.onload = function () {
            new TruliooClient({ publicKey: publicKey, accessTokenURL: accessTokenURL, handleResponse });
        };

也不起作用,因为即使在脚本中定义了TruliooClient也没有定义

1 个答案:

答案 0 :(得分:1)

好吧,对于寻求相同问题答案的任何人,我都可以使之工作。

我必须创建一个函数来在脚本加载后执行:

    function scriptLoaded() {
        new window.TruliooClient({
            publicKey,
            accessTokenURL,
            handleResponse,
        });
    }

我在useEffect里面叫它:

    useEffect(() => {
        const script = document.createElement('script');
        script.src = 'https://js.trulioo.com/latest/main.js';
        script.async = true;
        script.onload = () => scriptLoaded();

        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        };
    }, []);