2016-12-31 55 views
1

我想有一些代碼只對特定的URL集運行所有網站。對於我的生活,我無法弄清楚爲什麼每個網站點擊,它運行的代碼,並不限於我限制它的網站。的jQuery + Greasemonkey的:受影響,不僅限於「window.location.href.indexOf」

// ==UserScript== 
// @name  test 
// @namespace test1 
// @description test2 
// @include  https://* 
// @version  1 
// @grant  none 
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js 
// ==/UserScript== 


$(document).ready(function() 
{ if( (!window.location.href.indexOf("https://www.youtube.com") > -1) 
     && (!window.location.href.indexOf("https://www.google.com") > -1)  
    ) 
    { 
    alert("test"); 
    } 
}); 
+0

window.location.href.indexOf(「https://開頭www.youtube.com「)始終爲真,如果匹配則爲false。 true and false總是> -1 – Shanimal

回答

0

你就近了。剛剛嘗試宣告所有預期的URL中的數組:

的JavaScript:

var urls = [ 
    "https://www.youtube.com", 
    "https://www.google.com", 
    "https://fiddle.jshell.net", 
    ]; 

    urls.forEach(function(v) { 
    if (window.location.href.indexOf(v) >= 0) { 
     alert("test"); 
    } 
    }); 

的jsfiddle:

https://jsfiddle.net/nikdtu/hyj6gmgu/

+0

@computerguy:您的歡迎! :) –

0

var domains = [ 
 
    'http://stacksnippets.net', // *** 
 
    'http://stackoverflow.com', 
 
    'http://google.com', 
 
    'http://youtube.com' 
 
]; 
 
var href = window.location.href; 
 
var isListed = domains.some(function(v){ 
 
    // expecting href.indexOf(v) to return 0 on success 
 
    return !href.indexOf(v); 
 
}); 
 

 
console.log(window.location.href, isListed)

window.location.href.indexOf("https://www.youtube.com") // is 0 OR -1 

所以

!window.location.href.indexOf("https://www.youtube.com") // is true OR false 

true > -1 // is always true 
false > -1 // is always true 

像這樣的東西應該讓你在那裏。

var domains = [ 
    'http://stackoverflow.com', 
    'http://google.com', 
    'http://youtube.com' 
]; 
var href = window.location.href; 
var isListed = domains.some(function(v){ 
    return !href.indexOf(v); 
}); 

isListed // true 
+0

對不起,但這並沒有讓我更接近 – computerguy

+0

我也試過「!= -1」 – computerguy

+0

我會如何讓你最後一次編輯運行$(「.target」).hide(); – computerguy