开发者

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

Is it possible to determine this at run开发者_开发问答time?

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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜