javascriptgoogle-chrome-extensionchrome-extension-manifest-v3content-scriptbrowser-extension

event stopPropagation doesn't stop propagation


I am working on a chrome extension where I created a context script on a Notion Page.

If user is focused on an input inside context script and hits backspace/delete, character in input is deleted with a content on a Notion page. I fixed this issue by adding onKeyDown handler:

export const onKeyDown = (evt: React.KeyboardEvent) => {
  if (evt.key === 'Backspace') {
    evt.stopPropagation()
  }
}

Now, If user is focused on an input inside context script and hits backspace/delete, only input value is removed.

I came across another issue when it's not possible to paste text into input by pressing Ctrl+V or Cmd+V. When user is focused on an input inside context script and press Ctrl+V or Cmd+V, the text is pasted into Notion page instead of focused input. I tried to fix this by adding:

export const onKeyDownDefault = (evt: React.KeyboardEvent) => {
  if (evt.key === 'Backspace') {
    evt.stopPropagation()
  }
  // Ctrl+V or Cmd+V pressed?
  if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == 86) {
    console.log('stop propagate')
    evt.stopPropagation()
    // evt.preventDefault()
  }
}

But it didn't help. I can see the console output 'stop propagate', but the text is not pasted into input.


Solution

  • It might be because Notion is listeniing to the paste event instead, try to also stopPropagation for the paste event instead.

    Working example:

    <input type="text" id="input" />
    <script>
      document.addEventListener('paste', (event) => {
        console.log((event.clipboardData || window.clipboardData).getData('text'));
      });
      const elInput = document.getElementById('input');
      elInput.addEventListener('keydown', (ev) => ev.stopPropagation());
      elInput.addEventListener('paste', (ev) => ev.stopPropagation());
    </script>

    Non-working example:

    <input type="text" id="input" />
    <script>
      document.addEventListener('paste', (event) => {
        console.log((event.clipboardData || window.clipboardData).getData('text'));
      });
      const elInput = document.getElementById('input');
      elInput.addEventListener('keydown', (ev) => ev.stopPropagation());
    </script>