Basically what I'm trying to do is write a greasemonkey script so that if a link on a page is not a link I have on an ignore list to just open the link, if it is on the list then reload the page after 5 seconds here is what I tried so far
var url1 = $("span.capsulelink a:eq(0) ").attr("href");
var ignoreList = ["example1.com","example2.com"]
if (url1 !== ignoreList) {
window.open(url1);
} else {
setTimeout(function() {
location.reload();
},5000);
}
I know it's the ( url1 !== ignoreList
) part I am having trouble with, I just can not seem to find the right expression for that. Like I do not know how to say if url1
is not on the ignoreList
{do something}.
ignoreList.indexOf(url1) !== -1
This is another way of saying "is url
contained in the ignoreList
array?"
This is because the indexOf()
method of Array
returns the index of the element you're looking for, or -1
if the element doesn't exist.
To negate this, which is what you want to do, you write:
ignoreList.indexOf(url1) === -1
(ie is url1
not in ignoreList
?)
This is a good question, because the answer really isn't intuitive.
When you're starting to learn javascript
, some of the syntax patterns begin to look familiar.
But the javascript equivalent of PHP's
if (!in_array([ARRAY]));
simply isn't obvious at all - this is one syntax you just need to know.
Here is the javascript
you're looking for:
if (ignoreList.indexOf(url1) !== -1) {
[RELOAD PAGE CODE HERE]
}
else {
[OPEN THE LINK CODE HERE]
}
Here's why it works:
ignoreList.indexOf([VALUE])
looks through the ignoreList
array and searches through the array's items.
If one of those items is [VALUE]
, it returns the index of that item.
Importantly, if none of the items are [VALUE]
it returns -1
.
So, in order to establish that at least one of the items is [VALUE]
, you have to verify that the returned index definitely isn't -1
.
Consequently the condition you need to check for is:
if (ignoreList.indexOf(url1) !== -1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.