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:
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With