问题
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