Chrome 拡張機能、特に開発者モードの拡張機能を意図せず再読み込みすると、孤立したコンテンツが作成される可能性がありますスクリプト。これらのスクリプトはバックグラウンドで実行されたままですが、残りの拡張機能との通信が失われ、「拡張コンテキストが無効になりました」や「unchecked runtime.lastError」などのエラーが発生します。
孤立コンテンツ スクリプトは引き続き DOM メッセージを受信できます。削除するには:
1.新しいコンテンツ スクリプトからメッセージを送信:
2.孤立したスクリプトのリスナーの登録を解除します:
3.バックグラウンド スクリプト:
4.コンテンツ スクリプト:
5.ポップアップ スクリプト:
コード例:
background.js:
// Re-inject content script
chrome.runtime.onInstalled.addListener(() => {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(tabs[0].id, { file: 'content.js' });
});
});
content.js:
// Orphaned script detection and cleanup
var orphanMessageId = chrome.runtime.id 'orphanCheck';
window.dispatchEvent(new Event(orphanMessageId));
window.addEventListener(orphanMessageId, unregisterOrphan);
// Register named listeners
chrome.runtime.onMessage.addListener(onMessage);
document.addEventListener('mousemove', onMouseMove);
// Orphan flag and cleanup function
window.running = true;
function unregisterOrphan() {
if (chrome.runtime.id) {
// Not orphaned
return;
}
window.removeEventListener(orphanMessageId, unregisterOrphan);
document.removeEventListener('mousemove', onMouseMove);
try {
chrome.runtime.onMessage.removeListener(onMessage);
} catch (e) {}
return true;
}
popup.js:
async function sendMessage(data) {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (await ensureContentScript(tab.id)) {
return await chrome.tabs.sendMessage(tab.id, data);
}
}
async function ensureContentScript(tabId) {
try {
const [{ result }] = await chrome.scripting.executeScript({
target: { tabId },
func: () => window.running === true,
});
if (!result) {
await chrome.scripting.executeScript({
target: { tabId },
files: ['content.js'],
});
}
return true;
} catch (e) {}
}
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3