javascripttampermonkey

Edit the behavior of a button using Tampermonkey


document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('#spectate').accesskey = 'k';
});
<button class="MuiButtonBase-root MuiButton-root MuiButton-contained MuiButton-containedPrimary MuiButton-sizeMedium MuiButton-containedSizeMedium MuiButton-root MuiButton-contained MuiButton-containedPrimary MuiButton-sizeMedium MuiButton-containedSizeMedium main-btns css-1hw9j7s" tabindex="0" type="button" id="spectate" style="background-color: rgb(244, 67, 54); color: rgb(255, 255, 255); border: 2px solid rgb(244, 67, 54); padding: 10px 20px; font-size: 16px; cursor: pointer; width: 150px; height: 200px;">
  <i class="fas fa-eye"></i>
  Spectate
  <span class="MuiTouchRipple-root css-w0pj6f"></span>
</button>

I'm trying to add accesskey="k" to the button, so that when pressing Alt+K it is pressed.

I have searched on the internet how to edit the behavior of a button using Tampermonkey but all I could find is information on how to create a new button. Could you help me?

<button class="MuiButtonBase-root MuiButton-root MuiButton-contained MuiButton-containedPrimary MuiButton-sizeMedium MuiButton-containedSizeMedium MuiButton-root MuiButton-contained MuiButton-containedPrimary MuiButton-sizeMedium MuiButton-containedSizeMedium main-btns css-1hw9j7s" tabindex="0" type="button" id="spectate" style="background-color: rgb(244, 67, 54); color: rgb(255, 255, 255); border: 2px solid rgb(244, 67, 54); padding: 10px 20px; font-size: 16px; cursor: pointer; width: 150px; height: 200px;">
  <i class="fas fa-eye"></i>
  Spectate
  <span class="MuiTouchRipple-root css-w0pj6f"></span>
</button>

Solution

  • To do what you require, select the #spectate element from the DOM and set its accessKey property as required. Note that you will need to do this after the DOM has loaded, hence the DOMContentLoaded event handler in the following example:

    document.addEventListener('DOMContentLoaded', () => {
      document.querySelector('#spectate').accessKey = 'k';
    });
    <button class="MuiButtonBase-root MuiButton-root MuiButton-contained MuiButton-containedPrimary MuiButton-sizeMedium MuiButton-containedSizeMedium MuiButton-root MuiButton-contained MuiButton-containedPrimary MuiButton-sizeMedium MuiButton-containedSizeMedium main-btns css-1hw9j7s" tabindex="0" type="button" id="spectate" style="background-color: rgb(244, 67, 54); color: rgb(255, 255, 255); border: 2px solid rgb(244, 67, 54); padding: 10px 20px; font-size: 16px; cursor: pointer; width: 150px; height: 200px;">
      <i class="fas fa-eye"></i>
      Spectate
      <span class="MuiTouchRipple-root css-w0pj6f"></span>
    </button>

    Also note that your example HTML already has the accesskey="k" attribute within it - I'm going to assume this is a mistake in the question.