如果我在chrome扩展弹出工作期间关闭一个选项卡怎么办



我正在制作一个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>
}

我认为您正在寻找的是一个后台服务工作者,它侦听事件(您可以在doTask函数中触发它(,并且在空闲(完成所有任务(之前不会卸载。

您可以通过调用runtime.getBackgroundPage或发送消息(消息传递(来加载服务工作者。

相关内容

最新更新