Is it possible to reference a JavaScript file inside of a JavaScript function?
Therefore i am wanting to convert this:
<script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.5.3-crypto-sha1-hmac.js"></script>
<script type="text/javascript">
var hmacString = Crypto.HMAC(Crypto.SHA1, "Message", "Secret Passphrase", { asString: true });
</script>
In to:
function hmac (input){
var hmacString = Crypto.HMAC(Crypto.SHA1, "Message", "KEY", { asString: true });
return hmacString;
}
I am using a tool called Cast Iron, which therefore restricts JavaScript down to only a function, but i need to call an external file, to load the needed functionality.
Is this even possible?
If I understand correctly, yes you can access functions and classes from one JS file as long as the other class was loaded before you attempt to access it.
So, if some-javascript-file.js
has a function named getThings()
, then you can do this:
<script type="text/javascript" src="http://cdn.example.com/js/some-javascript-file.js"></script>
<script type="text/javascript">
var things = getThings(); // getThings is a publicly accessible function in an external class.
</script>
OK the screenshot kind of helps. It seems you want something from an external JS file, and to manipulate it inside this function.
So you could have one javascript file with:
var foo = 'foo'; //this is in the global scope
and then your other file has:
function hmac(key){
alert(document.foo);
}
should access what you want
Yes, you can load other js files with javascript. Depending on the load state where your function is executed, you may either use
document.write('<script type="text/javascript" src="http://crypto-js.googlecode.com/files/2.5.3-crypto-sha1-hmac.js"'+'><'+'/script>"');
// loads synchronouly and executes
Crypto.HMAC(...); // is available here
Watch out that document.write breaks the whole page once your DOM is loaded. You can also use:
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://crypto-js.googlecode.com/files/2.5.3-crypto-sha1-hmac.js";
s.onload = function() {
// the file should be executed now so
Crypto.HMAC(...); // is available here
};
document.head.appendChild(s); // load asychronously
See also Load js from external site on fly
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.