如果我在 chrome 扩展弹出窗口工作期间关闭标签页怎么办?
What if I close a tab during chrome extension popup working?
我正在制作一个 chrome 扩展程序来读取当前选项卡的内容并在后端执行繁重的任务。如果我在它的过程中关闭了一个选项卡怎么办?我想允许用户在不等待进程完成的情况下关闭选项卡。我的代码如下。它是用 React 和 Typescript 编写的。提前谢谢你。
import React from 'react';
export const PopupPage = () => {
const doTask = async(event: React.MouseEvent<HTMLButtonElement>) => {
chrome.tabs?.query({
active: true,
currentWindow: true
}, async tabs => {
const currentTab = tabs[0]
const currentUrl = currentTab.url
const currentTitle = currentTab.title
if (currentUrl === undefined) {
return
}
const creationOptions = {
type: 'basic' as chrome.notifications.TemplateType,
title: `Nice title`,
message: `Start a heavy process`,
iconUrl: './logo.png',
contextMessage: 'You can close the tab now.'
} as chrome.notifications.NotificationOptions<true>;
chrome.notifications.create(currentUrl, creationOptions)
// Send a url and title to backend and wait for it finishing.
await executeHeavyTaskAndWaitForResponseFromBackend(currentUrl, currentTitle)
const updateOptions =
{
type: 'basic' as chrome.notifications.TemplateType,
title: 'Nice Title',
message: "COMPLETED",
iconUrl: './logo.png'
}
// I want to be sure this notification is called even after the tab is closed
chrome.notifications.create(currentUrl, updateOptions)
});
}
return <button onClick={doTask}>Do a heavy task</button>
}
我想你要找的是 background service worker,它监听事件(你可以在你的 doTask
函数中触发它)并且在它空闲之前不会卸载(完成所有任务)。
您可以通过调用 runtime.getBackgroundPage
或发送消息 (message passing) 来加载 Service Worker。
我正在制作一个 chrome 扩展程序来读取当前选项卡的内容并在后端执行繁重的任务。如果我在它的过程中关闭了一个选项卡怎么办?我想允许用户在不等待进程完成的情况下关闭选项卡。我的代码如下。它是用 React 和 Typescript 编写的。提前谢谢你。
import React from 'react';
export const PopupPage = () => {
const doTask = async(event: React.MouseEvent<HTMLButtonElement>) => {
chrome.tabs?.query({
active: true,
currentWindow: true
}, async tabs => {
const currentTab = tabs[0]
const currentUrl = currentTab.url
const currentTitle = currentTab.title
if (currentUrl === undefined) {
return
}
const creationOptions = {
type: 'basic' as chrome.notifications.TemplateType,
title: `Nice title`,
message: `Start a heavy process`,
iconUrl: './logo.png',
contextMessage: 'You can close the tab now.'
} as chrome.notifications.NotificationOptions<true>;
chrome.notifications.create(currentUrl, creationOptions)
// Send a url and title to backend and wait for it finishing.
await executeHeavyTaskAndWaitForResponseFromBackend(currentUrl, currentTitle)
const updateOptions =
{
type: 'basic' as chrome.notifications.TemplateType,
title: 'Nice Title',
message: "COMPLETED",
iconUrl: './logo.png'
}
// I want to be sure this notification is called even after the tab is closed
chrome.notifications.create(currentUrl, updateOptions)
});
}
return <button onClick={doTask}>Do a heavy task</button>
}
我想你要找的是 background service worker,它监听事件(你可以在你的 doTask
函数中触发它)并且在它空闲之前不会卸载(完成所有任务)。
您可以通过调用 runtime.getBackgroundPage
或发送消息 (message passing) 来加载 Service Worker。