Minimal ChatGPT Message Logger + Injector + Submitter

Listen for postMessage from parent, log to console, enter it into the chat input, and submit

当前为 2025-05-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Minimal ChatGPT Message Logger + Injector + Submitter
  3. // @description Listen for postMessage from parent, log to console, enter it into the chat input, and submit
  4. // @match https://chatgpt.com/*
  5. // @version 0.0.1.20250515142156
  6. // @namespace https://greasyfork.org/users/1435046
  7. // ==/UserScript==
  8.  
  9. (function () {
  10. 'use strict';
  11.  
  12. window.addEventListener('message', function (event) {
  13.  
  14. // Handle search button clicks
  15. if (event.data && event.data.type === 'searchButtonClicked') {
  16. const searchBtn = document.querySelector('[data-testid="composer-button-search"]');
  17. if (searchBtn) searchBtn.click();
  18. return;
  19. }
  20.  
  21. if (event.data && event.data.type === 'reasonButtonClicked') {
  22. const reasonBtn = document.querySelector('[data-testid="composer-button-reason"]');
  23. if (reasonBtn) reasonBtn.click();
  24. return;
  25. }
  26.  
  27. if (event.data && event.data.type === 'newChatButtonClicked') {
  28. // Click the "New chat" anchor link
  29. const newChatLink = document.querySelector('a[aria-label="New chat"][href="/"]');
  30. if (newChatLink) newChatLink.click();
  31. return;
  32. }
  33.  
  34. // Only respond to string messages
  35. if (typeof event.data !== 'string') return;
  36.  
  37. // Locate ProseMirror composer
  38. const composer = document.querySelector('.ProseMirror');
  39. if (!composer) return;
  40.  
  41. console.log('Injecting message:', event.data);
  42.  
  43. // Focus and inject the text
  44. composer.focus();
  45.  
  46. const lines = event.data.split('\n');
  47. const html = lines
  48. .map(line => `<p>${line
  49. .replace(/&/g, '&amp;')
  50. .replace(/</g, '&lt;')
  51. .replace(/>/g, '&gt;')}</p>`)
  52. .join('');
  53. composer.innerHTML = html;
  54.  
  55. composer.dispatchEvent(new InputEvent('input', { bubbles: true }));
  56.  
  57. // Observe DOM changes until the send button is enabled
  58. const observer = new MutationObserver(function (mutations, obs) {
  59. const sendBtn = document.querySelector('[data-testid="send-button"]');
  60. if (sendBtn && !sendBtn.disabled) {
  61. obs.disconnect();
  62. console.log('Submitting message');
  63. sendBtn.click();
  64. }
  65. });
  66.  
  67. observer.observe(document, {
  68. childList: true,
  69. subtree: true,
  70. attributes: true,
  71. attributeFilter: ['disabled']
  72. });
  73. });
  74. })();