Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script tag in Aurelia view is not executed

I'm adding a simple script block to a simple aurelia view:

<template>
    <script type="text/javascript">
    alert('Hello!');
    </script>
</template>

The script is never run, even though the view is rendered correctly and I can see that the script block does appear in the DOM.

I have also tried dynamically inserting a script block via the viewModel and also tried with:

 <script type="text/javascript" src="http://blah"></script>

I understand it's not best practice to do this, but I'm trying to integrate a third party widget that will then render an iframe. The alert shown above is just a simple way of the verifying the issue that I'm seeing.

The real life scenario is as follows:

  • I make an api call to a third party from my view model.
  • The following is returned:

    <script type='text/javascript' language='JavaScript' src='https://secure.na1.echosign.com/public/embeddedWidget? ` wid=CBFCIBAA3AAABLblqZhBU33GaMRZ2lMelHKzti7RkanxMP5v- uW_f8CEiKoopNNofJWyXhmE56Su3HTbY*&token=CBNCKBAAHBCAABAARNiZ7Yba0h7dnLaQRBAdTdH9UrJZKryP' />

I need to append this to the DOM and have it execute. I am working around this issue by calling the above url via fetch and then I exec the response, but it seems like a tedious/hacky way of doing it.

like image 484
Sam Shiles Avatar asked Apr 09 '16 13:04

Sam Shiles


People also ask

How do you execute a script tag?

The “script” tag JavaScript programs can be inserted almost anywhere into an HTML document using the <script> tag. You can run the example by clicking the “Play” button in the right-top corner of the box above. The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag.

What is tag in script?

The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.


1 Answers

I would recommend adapting the solution provided in this answer: Use JS variable to set the src attribute for <script> tag.

In your VM's bind or attached method (most likely):

let scriptURL = api.getURL();

let scriptElement = document.createElement('script');

scriptElement.src = scriptURL;
scriptElement.onload = () => {
    // do anything you need to do here, or call a VM method
    this.someVMMethod();
};

this.scriptElementInHead = document.querySelector('head').appendChild(scriptElement);

If need be, you can even remove the script element by keeping a reference to it and removing it from the head element when the component is being unloaded in the unbind or detached methods.

 detached() {
   document.querySelector('head').removeChild(this.scriptElementInHead);
 }
like image 97
Ashley Grant Avatar answered Oct 14 '22 13:10

Ashley Grant