获取执行JavaScript文件的URL(主要是IE6-7问题) [英] Getting URL of executing JavaScript file (IE6-7 problem mostly)

查看:162
本文介绍了获取执行JavaScript文件的URL(主要是IE6-7问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

=http://gist.github.com/433486 =nofollow noreferrer> http://gist.github.com/433486

基本上你可以这样调用:

http://gist.github.com/433486

Basically you get to call something like this:

在页面上的外部JavaScript文件中,然后可以使用它做一些事情

getScriptName(function(url) { console.log(url); // http://www.example.com/myExternalJsFile.js });

它几乎在我测试的所有浏览器都工作得很好的一个标签(例如c $ c>< script> (Firefox,Chrome,Safari,Opera v10至少和IE 8)。

inside an external JavaScript file on a page and can then do something with it (like find the <script> tag that loaded it for example).

然而,在IE 6和7中似乎失败。回调函数执行,但检索的名称是到主HTML页面的URL,而不是JavaScript文件。继续示例, getScriptName 使用以下参数调用回调: http://www.example.com/index.html

It works great in almost all the browsers I've tested (Firefox, Chrome, Safari, Opera v10 at least, and IE 8).

所以我真正要问的是,如果有一些其他方式获取当前的JavaScript文件的URL(可能是IE 6和7特定的hackery) ?提前感谢!

It seems to fail, however, in IE 6 and 7. The callback function gets executed, but the retrieved name is the URL to the main HTML page, not the JavaScript file. Continuing with the example, getScriptName invokes the callback with the parameter: http://www.example.com/index.html

修改:此外,这并不适用于所有情况,因此请不要推荐:

So all I'm really asking is if there's some other way of getting the URL of the current JavaScript file (which could be IE 6 and 7 specific hackery)? Thanks in advance!

EDIT: Also, this won't work in every case, so please don't recommend it:

我想在动态创建的脚本标记的情况下工作

var scripts = document.getElementsByTagName("script"); return scripts[scripts.length-1].src;


推荐答案

对不起,我怀疑你可能会挣扎。 IE早于版本8通常会提供来自以下形式的JavaScript错误的错误消息:

Sorry, I suspect you might struggle with this. IE earlier than version 8 typically gives error messages from javascript errors of the form:

line: 342
char: 3
error: expected identifier, string or number
code: 0
url: http://example.com/path/to/resource

其中url是window.location.href,而不是包含问题的外部Javascript资源的URL。我建议IE给出无效的URL值,因为脚本URL在这一点上不可用于IE,并且它也不可用于您可能写的任何Javascript尝试显示它。

where the url is the window.location.href, rather than the URL of the external Javascript resource that contains the problem. I suggest that IE gives the unhelpful URL value since the script URL isn't available to IE at that point, and neither is it available to any Javascript you might write to try to display it.

我想能够链接到IE8发布说明,说这个错误/功能已经修复,因此我创建这个作为社区wiki的原因。我的MSDN foo是相当弱!

I would love to be able to link to IE8 release notes which say this bug / feature has been fixed, hence the reason I created this as community wiki. My MSDN foo is pretty weak!

这篇关于获取执行JavaScript文件的URL(主要是IE6-7问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆