Comparing an URL to a given list of URL schemes in Javascript
Using JavaScript I would like to check if a given URL matches a list of URL schemes. I have come this far:
function on_wikipedia() {
// the list of allowed locations
var allowed_locations = new Array( "http://*.wikibooks.org/*"
, "http://*.wikimedia.org/*"
, "http://*.wikipedia.org/*"
, "http://*.wikiquote.org/*"
, "http://*.wikiversity.org/*"
, "http://*.wiktionary.org/*"
, "http://www.mediawiki.org/*"
, "https://secure.wikimedia.org/*"
);
// current l开发者_如何学Pythonocation; e.g. "http://en.wikipedia.org/wiki/Main_Page"
var current_location = content.document.location;
var valid = false;
// compare current_location to allowed_locations and set valid to true,
// if it matches
//
// FIXME
return valid;
}
Maybe it is a bad idea to do it like this. Maybe I should use regular expressions to make the comparason? Unfortunately I'm lost... I have no JavaScript experience at all. Could someone please point me in the right direction?
function onWikipedia(){
// Untested
var allowedLocations = /^(?:http:\/\/(?:.+?\.wik(?:ibooks|imedia|ipedia|iquote|iversity|tionary)\.org|www\.mediawiki\.org)\/|https:\/\/secure.wikimedia.org\/)/i;
return allowedLocations.test( content.document.location );
}
The i
at the end of the regex makes it case-insensitive. Remove if you don't want that.
In general, the regex says this:
- Starting at the front of the string (
^
), look for either of the following ((?:...|...)
):http://
followed by either of the following, and then a literal slash (\/
)- basically anything (
.+?
) followed by a literal period (\.
) followed bywik
and then...oh, one of these domain names, followed by.org
, or www.mediawiki.org
- basically anything (
https://secure.wikimedia.org/
Note that the very permissive .+?
allows something like http://foo.bar.com/?.wikibooks.org/
to be matched. You probably want something more restrictive, such as letters, numbers, underscores, periods, or hyphens. If so, replace .+?
with [\w.-]+?
Alternatively, instead of testing against the entire URL, you might want to just check against the hostname:
function onWikipedia(){
if (location.protocol=='https:'){
return location.hostname == 'secure.wikimedia.org';
}else{
var regexp = /^(?:www\.wikimedia|.+?\.wik(?:ibooks|imedia|ipedia|iquote|iversity|tionary)\.org/i;
return regexp.test( location.hostname );
}
}
精彩评论