Reputation: 3227
Consider these script fragments.
<script data-name="script1">
foo();
</script>
<script data-name="script2">
foo();
</script>
<script>
function foo(){
// console.log(arguments.?);
}
</script>
Is there a way to find out which script function foo was called from the line denoted by the "//"?
Upvotes: 2
Views: 1715
Reputation: 36511
Ok, I figured it out, this will grab the script data-name attribute
function foo() {
var parentScript = document.body.lastChild;
console.log(parentScript.getAttribute('data-name'));
}
To get it to work I had to define the foo function above the calls to it, but I'm sure some playing around with it could resolve that.
Upvotes: 0
Reputation: 571
As already mentioned in the comments, the way you present it, this is not possible, it only works if the function foo
is called from a function, which then of course has to be a different function for each script, then you can use
console.log(arguments.callee.caller.name)
That will give you the name of the function that called your function foo.
Edit: and really, if it's important to know from where the script was called, just use an argument, like function foo(caller){
, which indicates how the function was called, that's much safer than relying on the arguments.callee.caller
thing.
Upvotes: 2