首页 > 解决方案 > chrome 扩展不允许 setDiscoverTargets

问题描述

我正在尝试开发一个 chrome 扩展,在这个扩展中,我需要与目标相关的事件(targetCreated/targetInfoChanged/targetDestroyed)。

为了实现这个目标,我通过chrome.debugger API 使用devtools 协议中的setDiscoverTargets方法。这是我正在使用的伪代码:

   // attach the debugger 
    
        chrome.debugger.attach(debuggeeId, version, onAttach);
    
    // when attach is successful send setAuthAttach to make setDiscoverTargets command work
        const onAttach = (debuggeeId) => {
            if (chrome.runtime.lastError) {
                alert(chrome.runtime.lastError.message);
                return;
            }
            console.log(`onAttach: ${JSON.stringify(debuggeeId)}`);
            chrome.debugger.sendCommand({ tabId: myTabId }, "Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, setAutoAttachHandler);
        }

// when auto attach handler is successful send setDiscoverTargets method      
// to enable targetCreated/targetInfoChanged/targetDestroyed events

        const setAutoAttachHandler = (result) => {
           if (chrome.runtime.lastError) {
               console.log("error in setAutoAttachHandler:" + chrome.runtime.lastError.message);
               return;
           }
           console.log(`setAutoAttachHandler result: ${JSON.stringify(result)}`);

            chrome.debugger.sendCommand({ tabId: myTabId }, 'Target.setDiscoverTargets', { discover: true }, setDiscoverTargetsHandler);
        }

    // see the result of command 
        const setDiscoverTargetsHandler = (result) => {
            if (chrome.runtime.lastError) {
                console.log("error in setDiscoverTargetsHandler:" + chrome.runtime.lastError.message);
                return;
            }
            console.log(`setDiscoverTargets result: ${JSON.stringify(result)}`);
        }

根据执行上面的代码,我总是收到not allowed错误

setDiscoverTargetsHandler 中的错误:{"code":-32000,"message":"Not allowed"}

并且不会触发与目标相关的事件。我还应该做些什么来获得这些事件吗?

谢谢你。

标签: google-chromegoogle-chrome-extensiongoogle-chrome-devtoolschromium

解决方案


从api发送命令时,不允许使用Target和域下的方法(Browser.getVersion 除外)。但是,如果您想观察附加了调试器的选项卡或打开了开发人员工具的选项卡,那么您可以定期轮询。你会得到回应,像这样:-Browserchrome.debuggerchrome.debugger.getTargets

[{
    "attached": true,
    "faviconUrl": "https://www.wikipedia.org/static/favicon/wikipedia.ico",
    "id": "DEA9ED6A4A3DFB9A6FC315AF7110465B",
    "tabId": 88,
    "title": "Wikipedia",
    "type": "page",
    "url": "https://www.wikipedia.org/,
}, {
    "attached": false,
    "faviconUrl": "https://github.githubassets.com/favicons/favicon.svg",
    "id": "3314432045C3EC141D4C7D7023606122",
    "tabId": 87,
    "title": "GitHub",
    "type": "page",
    "url": "https://github.com/"
}]

推荐阅读