仅在 url 索引上运行脚本

Run script only on index of url

本文关键字:运行 脚本 索引 url 仅在      更新时间:2023-09-26

这是一些脚本的片段,它允许它在包含特定字符串的URL上运行。

if(location.href.indexOf("MODULE=MESSAGE")>0||location.href.indexOf("/message")>0) { //GOOD TO GO
    if(location.href.indexOf("c=0")>0||location.href.indexOf("c=0")>0) chatLinkStyle = " style='display:none'";

我需要为脚本添加第二个余量才能在 indexOF("SEQNO") 上运行

以下是当前允许的页面的 URL 字符串

mysite/2015/55392?MODULE=MESSAGE1
mysite/2015/55392?MODULE=MESSAGE2
mysite/2015/55392?MODULE=MESSAGE3

等。。。。。MESSAGE20

这是除了当前之外,我想要允许的另一个 URL 字符串

mysite/2015/options?L=55392&O=247&SEQNO=0
mysite/2015/options?L=55392&O=247&SEQNO=1
mysite/2015/options?L=55392&O=247&SEQNO=2

等。。。SEQNO=20

不知道如何编辑上述内容以允许多个索引,请提供任何帮助。

只需添加多个 if 语句 (||)

    <script type="text/javascript">
var myurl = "http://yourwebsite.com/index.php";
var currenturl = window.location;
if(myurl == currenturl) {
    //run your code
}
</script>

一种更简洁的方法。这里的优点是您可以继续添加模式,而无需更改代码,例如添加另一个if条件等。

var allowedPatterns = [
    "MODULE=MESSAGE",
    "/message",
    "c=0",
    "SEQNO"
],
    href = location.href,
    valid = true;
for (var i=0, j = allowedPatterns.length; i<j; i++) {
    if ( href.indexOf(allowedPatterns[i]) === -1 ) {
        valid = false;
        break;
    }
};
if (valid) {
    //Your code
}