简体   繁体   中英

Trigger function from external js script into Vue

There is a script that is loaded into my Vue app inside the mounted hook, by this way:

let recaptchaScript = document.createElement("script");
recaptchaScript.setAttribute("src", "https://sso.****.com.co/v3/****.main.js");
document.body.append(recaptchaScript);

The script is loaded, but there is a function that is injected into the window object.

Currently when I need to use that function, I do this:

mounted() {
  let recaptchaScript = document.createElement("script");
  recaptchaScript.setAttribute("src", process.env.VUE_APP_TAPIT_SSO_URL);
  document.body.append(recaptchaScript);
  this.$nextTick(() => {
    setTimeout(() => {
      window.ssoApp.configApp(TAPIT_SSO_CONFIG);
    }, 1500);
  });

I want to get rid the setTimeOut, but I haven't figured it out yet how to wait for the script executes and inject that object of functions (ssoApp) into the window object without using a timer. Is there any way to do this? I've tried almost everything.

The element should have both src and an onload property. Set the source last, so that everything that can be done synchronously is done before starting to load.

mounted() {
  let recaptchaScript = document.createElement("script");
  document.body.append(recaptchaScript);
  recaptchaScript.onload = () => window.ssoApp.configApp(TAPIT_SSO_CONFIG);
  recaptchaScript.src = process.env.VUE_APP_TAPIT_SSO_URL;
}

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