Search code examples
jquerygreasemonkey

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


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

Solution

  • 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/