以下是实现该功能的Chrome扩展V3代码:

manifest.json

{
  "manifest_version": 3,
  "name": "Close Tab and Send ID",
  "version": "1.0",
  "description": "Close tab and send its ID to backend.",
  "permissions": [
    "tabs",
    "https://example.com/*"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

background.js

chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
  // Only send tab ID and close tab if it was not closed by window.close()
  if (removeInfo.isWindowClosing) {
    return;
  }
  
  // Send tab ID to backend
  fetch('https://example.com/close-tab', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      tabId
    })
  })
  .then(response => {
    if (response.ok) {
      // Close tab
      chrome.tabs.remove(tabId);
    } else {
      console.error('Failed to send tab ID to backend:', response.status, response.statusText);
    }
  })
  .catch(error => {
    console.error('Failed to send tab ID to backend:', error);
  });
});

这个扩展会在每次关闭标签页时,发送标签页的ID到指定的后台地址,并关闭此标签页。注意,这个扩展需要在manifest.json文件中添加对应的权限和后台地址。

chrome扩展V3 获取原始标签页的id发送给后台关闭此标签页 。实现代码

原文地址: http://www.cveoy.top/t/topic/bT8o 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录