Last active
March 31, 2025 17:43
-
-
Save salmin89/f706e4320c75d1f5cc5f40b70d86e116 to your computer and use it in GitHub Desktop.
Extension Message Streaming Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createElement } from 'react'; | |
import { renderToReadableStream } from 'react-dom/server'; | |
import Simple from '../components/Simple'; | |
async function streamReactComponent(tabId) { | |
const stream = await renderToReadableStream(createElement(Simple)); | |
// Initiate connection with content script | |
chrome.tabs.sendMessage(tabId, { type: 'START_REACT_STREAM' }); | |
const reader = stream.getReader(); | |
const decoder = new TextDecoder(); | |
while (true) { | |
const { done, value } = await reader.read(); | |
if (done) break; | |
const chunk = decoder.decode(value, { stream: true }); | |
// Send chunk to content script | |
chrome.tabs.sendMessage(tabId, { type: 'REACT_STREAM_CHUNK', chunk }); | |
} | |
chrome.tabs.sendMessage(tabId, { type: 'END_REACT_STREAM' }); | |
} | |
chrome.runtime.onMessage.addListener((message, sender) => { | |
if (message.type === 'REQUEST_REACT_STREAM') { | |
streamReactComponent(sender.tab.id); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createElement } from 'react'; | |
import { hydrateRoot } from 'react-dom/client'; | |
import Simple from './components/Simple'; | |
let streamContainer: Element = null!; | |
function createStreamContainer() { | |
streamContainer = document.createElement('div'); | |
streamContainer.id = 'react-stream-container'; | |
document.body.appendChild(streamContainer); | |
} | |
chrome.runtime.onMessage.addListener((message) => { | |
switch (message.type) { | |
case 'START_REACT_STREAM': | |
createStreamContainer(); | |
break; | |
case 'REACT_STREAM_CHUNK': | |
if (streamContainer) { | |
console.log(message.chunk); | |
streamContainer.innerHTML += message.chunk; | |
} | |
break; | |
case 'END_REACT_STREAM': | |
console.log('React component stream ended'); | |
hydrateComponent(); | |
break; | |
} | |
}); | |
function hydrateComponent() { | |
const container = document.getElementById('react-stream-container')!; | |
hydrateRoot(container, createElement(Simple)); | |
} | |
// Request the stream to start | |
chrome.runtime.sendMessage({ type: 'REQUEST_REACT_STREAM' }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment