javascript 使用Chrome扩展在YouTube上发送消息

d6kp6zgx  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(152)

我试图添加一个按钮,可以发送消息到实时聊天,但我不认为它找到适当的输入元素。
我添加了一些日志试图找到它。

const sendMessage = (message) => {
  console.log('Sending message:', message);
  const chatInputBox = document.querySelector('#input');
  console.log('Chat input box:', chatInputBox);
  chatInputBox.focus();
  chatInputBox.innerText = message;
  chatInputBox.dispatchEvent(new Event('input', { bubbles: true }));
  setTimeout(() => {
    const sendButton = document.querySelector('#button');
    console.log('Send button:', sendButton);
    if (sendButton) {
      console.log('Clicking send button');
      try {
        sendButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
      } catch (error) {
        console.error('Error sending message:', error);
      }
    } else {
      console.error('Could not find send button');
    }
  }, 1000);
};
};

content.js:42发送消息:Hello!content.js:44聊天输入框: content.js:50发送按钮:... flex content.js:52点击发送按钮

7eumitmz

7eumitmz1#

我让它与contentDocument一起找到输入和aria-label来单击发送按钮。

const sendMessage = (message) => {
  console.log('Sending message:', message);
  const liveChatFrame = document.querySelector('iframe.style-scope.ytd-live-chat-frame');
  const chatInputBox = liveChatFrame.contentDocument.querySelector('#input.yt-live-chat-text-input-field-renderer');
  console.log('Chat input box:', chatInputBox);
  chatInputBox.focus();
  chatInputBox.innerText = message;
  chatInputBox.dispatchEvent(new Event('input', { bubbles: true }));
  setTimeout(() => {
    const sendButton = liveChatFrame.contentDocument.querySelector('#button.yt-icon-button[aria-label="Send"]');
    console.log('Send button:', sendButton);
    if (sendButton) {
      console.log('Clicking send button');
      try {
        sendButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
      } catch (error) {
        console.error('Error sending message:', error);
      }
    } else {
      console.error('Could not find send button');
    }
  }, 1000);
};

相关问题