Skip to main content
 首页 » 编程设计

javascript之正则表达式捕获尽可能多的 Javascript 重定向

2025年05月04日26pander-it

我试图从许多 HTML 页面中捕获尽可能多的 Javascript 重定向。我的正则表达式是:

((location.href)|(window.location)|(location.replace)|(location.assign))(( ?= ?)|( ?\( ?))("|')([^'"]*)("|')( ?\) ?)?; 

我使用 Python,但问题很笼统:

regex = re.compile(r"""((location.href)|(window.location)|(location.replace)|(location.assign))(( ?= ?)|( ?\( ?))("|')([^'"]*)("|')( ?\) ?)?;""", re.I) 
# ... some control here ... 
print re.search(regex, html).group(10)  # 10 is the pure url 

我做了一些测试,我能够捕捉到所有这些情况。

location.href = "http://www.foo.com"; 
location.href="http://www.foo.com"; 
window.location = "http://www.foo.com"; 
window.location.href = "http://www.foo.com"; 
location.replace ("http://www.foo.com"); 
location.replace( "http://www.foo.com" ) ; 
location.assign ("http://www.foo.com"); 

并跳过我无法解析 URL 的地方,因为代码包含一个变量:

location.href = "http://www.foo.com" + var + "something else"; 

问题是:

  1. 还有其他方法可以使用 Javascript 进行重定向吗?我缺少的其他 location.somethingelse?
  2. 我捕捉这 4 个案例的方式是否正确?是否允许使用类似 location.href = http://www.foo.com; 或 location.replace (http://www.foo.com); 我会因为(双)引号而错过?我是太严格了还是太松懈了?
  3. 我的正则表达式写得好吗?或者我可以通过某种方式改进它吗?

请您参考如下方法:

一般来说,您不能使用正则表达式解析编程语言(好吧,理论上是 you can ,但这是非常不切实际的)。对于 javascript 尤其如此,因为它具有高度动态的特性。例如,

 window['loc' + 'a' + 'tion'][['h','r','e','f'].join('')] = 'something'.replace(/s/, etc...) 

也就是说,这里有一个表达式至少可以通过您的测试(为清楚起见进行了分解):

# quoted string 
str = r""" 
    ' (?:\\.|[^'])* ' 
    | 
    " (?:\\.|[^"])* " 
""" 
# dotted reference to "location" 
loc = r""" 
    (?: \w+\.)* 
    \b location \b 
    (?: \.\w+)* 
""" 
 
# ref=string or ref(string) 
expr = r""" 
    ({0}) 
    \s* 
    (?: 
        = \s* ({1}) 
        | 
        \( \s* ({1}) \s* \) 
    ) 
    \s* 
    ; 
""".format(loc, str) 

在扩展模式下编译它,例如

expr = re.compile(expr, re.X)