3

I'm not a programmer, but my work requires that I open multiple tabs at once. Whenever I find a certain word in a tab, I need to close it. enter image description here

An example would be closing the tab for this page: http://ebay.com/itm/292769440348 if it has the word "ended" in it. I am currently trying the below script, but the tab closes even when the word "ended" is not detected.

Browser: Brave and Chrome Extension: Tempermonkey

$("div:contains('ended')").each(function()
{
   window.close()
});

Can you explain which part I have wrong in my code?

Rashad Saleh
  • 2,686
  • 1
  • 23
  • 28
user3546314
  • 124
  • 1
  • 13
  • 2
    "whenever find the certain word" where you want to find certain work! Question not clear – Dupinder Singh Sep 10 '19 at 05:18
  • 1
    Can you provide an example page that closes when it shouldn't? I'm not sure about brave debug tools but probably you can simply enter `$("div:contains('close')")` in the dev tools and take a look at the results on the specific page to see what results you are getting that you don't expect. – Patrick Fay Sep 10 '19 at 05:26
  • Like this page https://www.ebay.com/itm/163725631245, it's have word "ended" . I want every time detect ended that tab will automatic close. I also will use this script to other page too. – user3546314 Sep 10 '19 at 05:32
  • 2
    In your question you were asking about false positives - sites that close that SHOULDN'T close. This is probably because your search is very broad - any instance of the word "close" or "ended" or whatever the word is will close the page. If you know more about the website you're on you can make a much more specific bit of code. For instance for ebay you could inspect the "Ended: " element and do a selection that more specifically targets that element `$(".u-flL.lable:contains('Ended')")` – Patrick Fay Sep 10 '19 at 05:41
  • I update my question.Thanks Patrick, you help me today – user3546314 Sep 10 '19 at 05:52

3 Answers3

3

Try this example:

if(document.body.innerText.replace(/\s+/g,' ').includes('end')){
   window.close()
}
Mat.Now
  • 1,715
  • 3
  • 16
  • 31
2

Not all websites use jQuery, and therefore your code will only work for some websites but not for all (and that is not saying that it is correct in the first place). Fortunately however, the correct code (which is based on the answer here by Milchkanne) is even simpler without jQuery:

if (document.body.innerHTML.search("ended") !== -1) {
  window.close()
}
Rashad Saleh
  • 2,686
  • 1
  • 23
  • 28
2
var body = document.querySelector('body');
if (body.innerText.indexOf('ended') > -1) {
    window.close()
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Kawaljit Singh
  • 190
  • 1
  • 6