JavaScriptが実行されたページのURLの取得、別サイトにある外部JavaScriptファイルで自身のURLを取得

更新:

JavaScriptが実行されたページのURLの取得、別サイトにある外部JavaScriptファイルで自身のURLを取得。window.location.hrefほか。

JavaScriptが実行されたページのURLを取得

http://example.com/test.html にてHTML中または外部ファイルを使って以下のJavaScriptを実行する。
console.log(window.location.href);
console.log(location.href);//windowは省略できる
console.log(document.documentURI);//IEだとundefined
console.log(document.location.href);
console.log(document.URL);
結果はすべて http://example.com/test.html となる。
これは別サイト(別サーバー)にある http://example.net/abc.js などで location.href を取得しても http://example.com/test.html となる。


別サイトにある外部JavaScriptファイルで自身のURLを取得

では http://example.com/test.html で別サイトにある http://example.net/abc.js を使い、JavaScriptファイル自身のURL(http://example.net/abc.js)を取得するにはどうしたらいいのか。
方法を探していたら http://qiita.com/kijtra/items/472cb34a8f0eb6dde459 を見つけた。
もとは http://stackoverflow.com/questions/984510/what-is-my-script-src-url/984656#984656 にあるもの。
<!-- http://example.com/test.html -->
<script src="http://example.net/abc.js"></script>
/* http://example.net/abc.js */
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];

if(script.src){
	script.insertAdjacentHTML('afterend',
		'<img style="border:none" '
		+ 'src="' + script.src.replace(/\.js$/, '.php') + '?'
		+ 'screenwidth=' + screen.width + '&'
		+ 'screenheight=' + screen.height + '&'
		+ 'referer=' + encodeURIComponent(document.referrer)
		+ '" />'
	);
}
要するにHTML中の自身の<script>要素のsrcを取得している。
最終的に私がやりたいのは、その.jsファイルと同じサーバーにあるPHPを実行すること。
上の例では.jsを.phpに置換して、.jsと同名のPHPファイルを<img>のsrcに指定している。
以前は.jsファイルの中にPHPファイルのパス(URL)を書いていたが、いろいろなサイトで使う際、それを書き換える必要があり、それをなくしたかった。
HTML中に<script>要素が複数あっても一応動作している。
<script>要素にidやclassを書くのはあまり見ないが、一応getElementByIdやgetElementsByClassNameで要素を特定することもできる。
まあ、HTML中に直にスクリプトを書けば済む話だが、外部ファイルで処理したかったので、とりあえず出来て良かった。

このエントリーをはてなブックマークに追加