jQuery+Greasemonkey: All sites affected, not limited to “window.location.href.indexOf”

橙三吉。 提交于 2019-12-24 07:53:59

问题


I'm trying to have code ran only on specific set of URLs. For the life of me I can not figure out why every website I click, it runs the code, and not limited to the sites I limit it to.

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

回答1:


You were close. Just try declaring all the intended urls in an array :

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/




回答2:


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

so

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

and

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

Something like this should get you there.

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


来源:https://stackoverflow.com/questions/41406232/jquerygreasemonkey-all-sites-affected-not-limited-to-window-location-href-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!