How to get the path to the currently running script with Javascript?

We have an IE extension implemented as a browser helper object (BHO). We have a utility function written in C ++ that we add to the page window object so that other scripts on the page can use it to load local script files dynamically. However, in order to resolve relative paths to these local script files, we need to determine the path to the JavaScript file that calls our function:

  • myfunc() written in C ++ and displayed on a JavaScript page
  • File: ///path/to/some/javascript.js
  • (additional stack frames)

From the top frame, I want to get information that the script call myfunc() is located in the file: ///path/to/some/javascript.js.

At first, I expected that we could just use the IActiveScriptDebug interface to get the stack from our utility function. However, it is not possible to get the IActiveScript interface from the IWebBrowser2 interface or a linked document (see Full Column for Multiple JS Frames in IE8 ).

The only thing I can think of is to register our own script debugging implementation, and myfunc() break into the debugger. However, I am skeptical that this will work without asking the user if they want to break into the debugger.

Before doing more thorough tests of this approach, I would like to check if anyone has final information on whether this can work and / or can offer an alternative approach that will allow a function written in C ++ to get a stack trace from the scripting engine that called it.

+6
source share
2 answers

This answer describes how I solved the actual problem described in the original question. The description of the question is not very large, since I made assumptions on how to solve the problem, which actually turned out to be unreasonable. What I'm really trying to do is determine the path to the current script run. I changed the name of the question to more accurately reflect this.

This is actually quite easy to achieve, as scripts are executed in the HTML document as they are loaded. Therefore, if I am currently executing JavaScript loaded with a script tag, this script tag will always be the last script tag in the document (since the rest of the document is not loaded yet). To solve this problem, just get the src attribute URL of the last script tag and resolve any relative paths based on this.

Of course, this does not work for a script embedded directly in the HTML page, but this is bad practice anyway (IMO), so this does not seem like a very important limitation.

0
source

Each loaded script can have an identifier, and each script call method myfunc () can pass this id to myfunc (). This means that you must first change myfunct () and finally change your scripts and calls.

+1
source

Source: https://habr.com/ru/post/917367/


All Articles