メッセージパッシング詳細
メッセージパッシング詳細
Section titled “メッセージパッシング詳細”メッセージパッシングは、拡張機能の異なるコンポーネント間で通信するための仕組みです。
基本的なメッセージパッシング
Section titled “基本的なメッセージパッシング”1. ワンタイムメッセージ
Section titled “1. ワンタイムメッセージ”// Content Script → Backgroundchrome.runtime.sendMessage( { type: 'GET_DATA', key: 'user' }, (response) => { console.log('Response:', response); });
// Background → Content Scriptchrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.tabs.sendMessage(tabs[0].id, { type: 'UPDATE_UI' }, (response) => { console.log('Response:', response); });});2. メッセージの受信
Section titled “2. メッセージの受信”// Background Scriptchrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === 'GET_DATA') { chrome.storage.local.get([message.key], (result) => { sendResponse({ data: result[message.key] }); }); return true; // 非同期レスポンスのため }});
// Content Scriptchrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === 'UPDATE_UI') { document.body.style.backgroundColor = 'blue'; sendResponse({ success: true }); }});長期的な接続
Section titled “長期的な接続”// Content Scriptconst port = chrome.runtime.connect({ name: 'content-script' });
port.postMessage({ type: 'INIT' });
port.onMessage.addListener((message) => { if (message.type === 'UPDATE') { // UIの更新 }});
// Background Scriptchrome.runtime.onConnect.addListener((port) => { console.log('Connected:', port.name);
port.onMessage.addListener((message) => { if (message.type === 'INIT') { port.postMessage({ type: 'READY' }); } });
port.onDisconnect.addListener(() => { console.log('Disconnected'); });});実践例: 双方向通信システム
Section titled “実践例: 双方向通信システム”class MessageBus { constructor() { this.listeners = new Map(); this.setupListener(); }
setupListener() { chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { const { type, payload } = message;
if (this.listeners.has(type)) { const handler = this.listeners.get(type); const result = handler(payload, sender);
if (result instanceof Promise) { result.then(response => sendResponse(response)); return true; } else { sendResponse(result); } } }); }
on(type, handler) { this.listeners.set(type, handler); }
off(type) { this.listeners.delete(type); }
send(type, payload) { return new Promise((resolve) => { chrome.runtime.sendMessage({ type, payload }, (response) => { resolve(response); }); }); }
sendToTab(tabId, type, payload) { return new Promise((resolve) => { chrome.tabs.sendMessage(tabId, { type, payload }, (response) => { resolve(response); }); }); }}
// 使用例const messageBus = new MessageBus();
messageBus.on('GET_USER_DATA', async (payload, sender) => { const userData = await getUserData(); return { userData };});
// 他のコンポーネントから呼び出しconst response = await messageBus.send('GET_USER_DATA', { userId: 123 });エラーハンドリング
Section titled “エラーハンドリング”// メッセージ送信時のエラーハンドリングfunction sendMessageSafe(type, payload) { return new Promise((resolve, reject) => { chrome.runtime.sendMessage({ type, payload }, (response) => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(response); } }); });}
// 使用例try { const response = await sendMessageSafe('GET_DATA', { key: 'value' }); console.log('Response:', response);} catch (error) { console.error('Error:', error);}