jQuery + Greasemonkey:所有受影响的网站,不限于" window.location.href.indexOf"

时间:2016-12-31 07:01:16

标签: jquery greasemonkey

我试图让代码只在特定的URL集上运行。对于我的生活,我无法弄清楚为什么我点击的每个网站,它运行代码,而不仅限于我限制它的网站。

// ==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");
  }
});

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你很亲密。只需尝试声明数组中的所有预期URL:

JavaScript:

prototype

JSFiddle:

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