【问题标题】:Using the same userscript to run different code at different URL's使用相同的用户脚本在不同的 URL 上运行不同的代码
【发布时间】:2018-02-02 17:28:09
【问题描述】:

我知道可以通过添加 @include 语句在不同的 URL 上运行脚本,但是可以根据 URL 运行不同的代码集吗?

我的脚本目前工作正常,但我不得不将它分成 5 个单独的用户脚本,感觉有点草率。

【问题讨论】:

    标签: javascript greasemonkey userscripts tampermonkey greasemonkey-4


    【解决方案1】:

    要根据 URL 切换运行的代码,请针对 the location objectDoc 的部分使用 if()switch() 语句。

    为避免误报和副作用,最好只测试最具辨别力的属性(通常是hostname 和/或pathname)。

    例如,对于在不同站点上运行的脚本:

    if (/alice\.com/.test (location.hostname) ) {
        // Run code for alice.com
    }
    else if (/bob\.com/.test (location.hostname) ) {
        // Run code for bob.com
    }
    else {
        // Run fall-back code, if any
    }
    
    // Run code for all sites here.
    


    或者,对于同一站点,不同的页面

    if (/\/comment\/edit/.test (location.pathname) ) {
        // Run code for edit pages
    }
    else if (/\/comment\/delete/.test (location.pathname) ) {
        // Run code for delete pages
    }
    else {
        // Run fall-back code, if any
    }
    
    // Run code for all pages here.
    


    注意使用转义\
    .test() 用于正则表达式的强大功能。例如,
    /(alice|bob)\.com/.test (location.hostname)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-28
      • 2012-04-05
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多