0

我正在从 chrome 扩展程序测试 Chrome DevTools 协议,但我在Emulation.setFocusEmulationEnabled工作时遇到了麻烦。这是我的测试扩展:

清单.json

{
  "name": "test",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["*://*/*"],
  "permissions": ["debugger", "tabs"]
}

背景.js

chrome.debugger.onDetach.addListener((source, reason) => {
    console.log("Debugger detached", source, reason);
});

chrome.tabs.onCreated.addListener((tab) => {
    console.log("Attaching debugger", tab.id);
    chrome.debugger.attach({ tabId: tab.id }, "1.3", () => {
        if (chrome.runtime.lastError) {
            console.log('runtime.lastError', tab.id, chrome.runtime.lastError.message);
            return;
        }
        console.log("Debugger attached", tab.id);
        //setTimeout(() => {
            chrome.debugger.sendCommand({
                tabId: tab.id
            }, "Emulation.setFocusEmulationEnabled", {
                enabled: true
            }, (result) => {
                if (chrome.runtime.lastError) {
                    console.log(chrome.runtime.lastError.message);
                }
                console.log('Command sent:', JSON.stringify(result));
            });
        //}, 2000);
    });
});

chrome.runtime.onInstalled.addListener(async () => { run() });
chrome.runtime.onStartup.addListener(async () => { run() });

async function run() {
    chrome.tabs.create({ url: 'about:blank', active: true, index: 0 }).then((tab) => {
        console.log(`Created tab ${tab.id}.`);
    });
}

为了测试它,我加载了解压后的扩展,扩展打开了一个新选项卡,我按 F12 打开 devtools 并输入document.hasFocus(),结果是false. 然后我打开Settings > More Tools > Extensions并检查服务人员视图。我在那里运行:

        chrome.debugger.sendCommand({
            tabId: XX
        }, "Emulation.setFocusEmulationEnabled", {
            enabled: true
        }, (result) => {
            if (chrome.runtime.lastError) {
                console.log(chrome.runtime.lastError.message);
            }
            console.log('Command sent:', JSON.stringify(result));
        });

将 XX 替换为 console.logs 中显示的选项卡 ID,然后我返回选项卡控制台,现在document.hasFocus()返回true.

为什么当我从控制台运行它而不是从扩展程序运行它时它工作?我尝试添加一个 setTimeout() 以确保完成创建选项卡,但得到了相同的结果。

4

0 回答 0