Could not include javascript file dynamically using angular4 and Javascript - javascript

I am unable to include one javascript file dynamically inside angular4 submit method. I am explaining my code below.
onTextFormSubmit(){
this.processValidation = true;
if (this.textForm.invalid) {
return;
}
let urlValue = this.textForm.value;
let url = urlValue.url;
console.log('hello',url);
var script = document.createElement("SCRIPT");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", url);
script.setAttribute('integrity', 'sha384-tEgmOghGBnPJQ3h63qzTE8V69SDVkIIyQeOFDfsG+AWJqA/UfZMmyQcXQVunl3wT');
script.setAttribute('crossorigin','anonymous');
document.getElementsByTagName("head")[0].appendChild(script);
}
Here the url parameter is coming from form submit which is like https://code.jquery.com/jquery-2.2.4.min.js this and I am including it dynamically but after submit when I am doing view page source and searching that file isnide the head tag, I did not found there which is my issue. I need to include this file dynamically.

Iv'e tested it in my environment and it also failed.
Iv'e got the following error:
Failed to find a valid digest in the 'integrity' attribute for
resource 'https://code.jquery.com/jquery-2.2.4.min.js' with computed
SHA-256 integrity 'BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44='. The
resource has been blocked.
After a little search I found this git issue that resolved it.
Simply add the following attribute to your script:
script.setAttribute('integrity','');
Edit:
If it's still doesn't work try this :
script.setAttribute('integrity','sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=');
script.setAttribute('crossorigin','anonymous');

Related

Can I use the link given by chrome.runtime.getURL in script.src?

I'm trying but even though it's proper link, the script fails. Why?
script = document.createElement('script')
script.src = chrome.runtime.getURL("my_file_from_extension.js")
console.log(script.src) // proper usable link
document.body.appendChild(script) // GET chrome-extension://invalid/ net::ERR_FAILED
I pasted "my_file_from_extension.js" into manifest's web_accessible_resources and it solved the issue.

Dynamically executing a <script> tag with an external src attribute using eval

I'm using the Genius API to retrieve the lyrics for a given song and embed them within an HTML <div> tag. I'm interacting with this API using PHP, via an AJAX GET request.
In the event of a successful AJAX request, I retrieve the following HTML from my PHP:
<div id='rg_embed_link_2351532' class='rg_embed_link' data-song-id='2351532'>
Read <a href='https://genius.com/The-1975-the-sound-lyrics'>“The Sound” by The 1975</a> on Genius
</div>
<script crossorigin src='//genius.com/songs/2351532/embed.js'></script>
The script tag returned by the Genius API will embed the lyrics and lyric information when executed.
I'm attempting to import this HTML into my already existing <div>. In this case, the <script> portion will not be executed. I've tried to use an eval() within the 'success' function of my AJAX to dynamically execute this script, but I'm having no success:
$.ajax({
url: 'lyrics.php',
type: 'GET',
async: true,
success: function(success){
geniusHTML = success;
//Insert geniusHTML including script tag into div
var lyricsDiv = document.getElementById("lyricsDiv");
lyricsDiv.innerHTML = geniusHTML;
//Get the script tag from the html and use eval on it
var innerScript = lyricsDiv.getElementsByTagName('script')
eval(innerScript.outerHTML);
}
});
I've tried to eval the:
.outerHTML -- The console shows this value to be: <script crossorigin="" src="//genius.com/songs/2351532/embed.js"></script>
.innerHTML -- Attribute appears to be empty.
.src -- The console shows this value to be: http://genius.com/songs/2351532/embed.js. Theeval() function errors on this with Uncaught SyntaxError: Unexpected end of input.
I feel I am potentially doing this backward. Should I execute the script from my AJAX return before I add it to the div? (The script generates quite a few embed div tags)
EDIT
With instruction from answerer Sjoerd de Wit, I attempted to create a new script tag from the source tag's src attribute, and add it via document.head.appendChild. This did not work, providing the warning:
Failed to execute 'write' on 'Document': It isn't possible to write
into a document from an asynchronously-loaded external script unless
it is explicitly opened.
You should get the src from the script tag and dynamically create and load it in your html
var script = document.createElement("script");
var innerScript = lyricsDiv.getElementsByTagName('script')
script.src = innerScript.src;
document.head.appendChild(script);
using jQuery's .html() instead of javascript's .innerHTML() will automatically evaluate scripts inside the string
so, try to change this line
//Insert geniusHTML including script tag into div
var lyricsDiv = document.getElementById("lyricsDiv");
lyricsDiv.innerHTML = geniusHTML;
//Get the script tag from the html and use eval on it
var innerScript = lyricsDiv.getElementsByTagName('script')
eval(innerScript.outerHTML);
into
$("#lyricsDiv").html(geniusHTML);
SOLUTION
Answering my own question.
The other answers to this question are perfectly acceptable and work in most situations. However, if the external .js file contains a document.write within it, your browser will give you the following warnings:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
One of the ways to get around this is to use Postscribe. Postscribe will override any instances of document.write within javascript passed to it.
In the context of my code -- which, rest assured, I will refactor to make it more efficient -- I retrieve my script tag from my div by getting the outerHTML of the element, then I pass it into postscribe.
With this use case, postscribe takes two arguments; the div to pass the script to, and the script itself. Of course -- you can pass the script inline or via a variable as I have done in the below example:
var myScript = myDiv.getElementsByTagName('script')[0].outerHTML;
postscribe('#myDiv', myScript);
Please see the postscribe documentation linked above for installation instructions and further functionality.

Js is not loading 2 times, in Angular2

I have already mention my js file path in angular.cli, it was loading only one time when angular app was initilizing and when we get back to the component then it was not loading so please give me some suggestion over this.
Thanks for your help in advance.:)
This imay help for you.
Please try to mention it on Index.html. or load script dynamatically on component.
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}

How do you retrieve data from parse.com to a script in photoshop?

So I made a script for photoshop to create signs, and I have alot of data from parse.com that I want to use in that script I made for photoshop. My problem is how do I get that data into the script so that I am able to use it?
I've tried
var parseI = document.createElement("script");
parseI.src = "http://www.parsecdn.com/js/parse-1.4.0.min.js";
parseI.type = "text/javascript";
document.appendChild(parseI);
But I get an error saying that document is undefined. I have no idea how to do this.
Try using document.body.appendChild(parseI) instead of just document.appendChild().
Look here for more info

problems when creating a script tag to a local file in android webview

I have an Android application that consist in a simple WebView that load a local html file in the assets folder of the project.
The HTML has a tag that calls (AJAX) an external service and expects as a response a String that represent a .js filename (say, 'test.js').
In test.js there is a simple funcion declaration, as:
var testFunction = function(){
// some code here
}
The AJAX callback then construct via javascript a tag that points to the .js file and append it to the head of the document; then call the testFunction:
$.ajax('externalService').done(function(response){
var script = // construct the script tag;
$('head').append(script);
testFunction();
});
Important: the script tag points to an external .js file, like
<script src="http://justatest.com/test.js">
... and all works fine!
Now i try to do the same thing putting the test.js inside the assets folder of the project. Obviously i changed the src of the script created in the callback with a relative path:
<script src="test.js"></script>
but when i try to invoke the function testFunction i get an error (testFunction is not defined).
The local path is correct (i put jquery.js in the same local folder of test.js and loaded it directly in the html with a with no errors).
I put all the attributes (like type="text/javascript") in the tag as well...
so, why the webview doesn't load a local .js file in this way?
thank you :)
EDIT: I tried the solution found in this thread:
jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources
and it worked!!!!
I tried the solution found in this thread:
jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources
and it worked!
I report the solution:
var scriptUrl = "test.js";
var head = document.getElementsByTagName("head")[0];
script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptUrl;
script.onload = function() { alert("Success"); };
script.onerror = function(e) { alert("failed: " + JSON.stringify(e)); };
head.appendChild(script);
So if i use the jquery append() method it doesn't work, but if i use the javascript appendChild method it work...

Categories