UICodes
UICodes

Reputation: 141

Determine HTML page that called a function in an external js file

Is it possible to determine this at runtime?

contents of external.js:

function x() {

  //can i get the path/name of the html file that included this js file?

  //which is test.html

}

contents of test.html

script src="external.js"

Upvotes: 1

Views: 1422

Answers (1)

bobince
bobince

Reputation: 536379

The “HTML file that included this js file” is easy, it's simply the address of the current document. location.href.

If you want to get a particular part of the URL, eg. the last part of the pathname:

var filename= location.pathname.split('/').pop();

The HTML page that called a function is a slightly different proposition, because in the world of cross-document scripting you can pass a function from one window to another, and so call the function from a different place to that where it was defined.

There's no simple or reliable way to detect where you've been called from, but this situation is generally not that common. In general it's best to avoid cross-document function calling as there are a number of nasty traps. window.postMessage should reduce the need for this in the future.

Upvotes: 5

Related Questions