2

When I Ctrl+click on an email in Gmail, that email opens in a new tab. In that tab, there is a "mark as unread" button. How to make a userscript that automatically clicks that button when the tab opens? I'm trying to adapt a similar script as follows:

// ==UserScript==
// @name         Auto-mark email as unread
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  -
// @author       You
// @match        https://mail.google.com/mail/u/0/?ui=2&view=btop&*
// @grant        none
// ==/UserScript==

setTimeout(function() {
    document.querySelector('.bAP').click()
    alert("Hi");
}, 3000);

The script shows the alert box, but doesn't click the button. Same with '#bAP'.

root
  • 1,812
  • 1
  • 12
  • 26
  • 1
    Unfortunately, the question you linked is flat-out wrong. There is no way that the code listed in the question would not work if the code in the answer did. But the code in the answer is brittle as all [censored]. Use the techniques of: https://stackoverflow.com/questions/15048223/choosing-and-activating-the-right-controls-on-an-ajax-driven-site – Brock Adams Aug 10 '19 at 14:46
  • The element you are looking for doesn't react to click events. It has eventlisteners of mousedown, mouseup, etc. though. – CennoxX Aug 13 '19 at 16:19
  • 1
    @CennoxX Yeah, this is the pain of trying to make userscripts for complex web application. Nothing acts like normal HTML website any more. Clicks are often listened for on `` as individual up/down actions etc. We really need some tools for simulating real user interaction in Tampermonkey. – Tomáš Zato Aug 15 '19 at 16:12
  • OP did the solution in the answer help you? It worked for me. – Tomáš Zato Aug 24 '19 at 11:12
  • @Tomáš Since it worked for you and my selector is wrong, could you please post the entire code? – root Oct 07 '19 at 13:36
  • @root I would post it if I ever had it. For the example in the answer, I used temporary variable from the dev tools. – Tomáš Zato Oct 07 '19 at 14:14

1 Answers1

1

So, this was actually easier than I expected, the following code seems to work:

const downEvt = new MouseEvent("mousedown");
const upEvt = new MouseEvent("mouseup");
button.dispatchEvent(downEvt);
setTimeout(()=>button.dispatchEvent(upEvt));
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Keep in mind, that the selector in the question `document.querySelector('.bAP').click()` is also false. it should be something like `document.querySelector('.J-J5-Ji .bvt')`. – CennoxX Aug 16 '19 at 07:28
  • @CennoxX I left the selector as an exercise to the reader after I found the page uses frames, meaning you have to find which frame has the button in it. – Tomáš Zato Aug 16 '19 at 08:10