从Chrome远程调试协议访问JavaScript变量

时间:2014-05-07 13:47:00

标签: javascript google-chrome remote-debugging

我通过Remote Debugging Protocol连接到Chrome(34.0.1847.132),并且我已成功启用运行时和控制台调试。我可以发送Chrome消息并收到回复。

现在,我想检查当前页面中某个JavaScript变量的属性。因此,在我的HTML页面中,我在脚本标记中有以下语句:

window.foo = {
  'bar' : 'baz'
}

我可以在Chrome本身的控制台中使用window.foo.bar查询该属性,但由于收到错误,我无法通过远程调试来执行此操作。

要获取属性,我将此JSON消息发送到WebSocket:

{
  :method => "Runtime.getProperties", 
  :params => {
    :objectId => "window.foo.bar"
  }, 
  "id"=>2
}

我收到回复:

{
    "error" => {
           "code" => -32000,
        "message" => "Inspected frame has gone"
    },
       "id" => 2
}

同样,如果我尝试Runtime.evaluate表达式window.foo.bar,我会得到:

{
    "result" => {
           "result" => {
                   "type" => "object",
               "objectId" => "{\"injectedScriptId\":1,\"id\":1}",
              "className" => "TypeError",
            "description" => "TypeError: Cannot read property 'bar' of undefined"
        },
        "wasThrown" => true
    },
        "id" => 2
}

什么会导致"检查框架"要走了?甚至是什么? 或objectId完全不同的东西?

如何访问JavaScript变量的属性呢?

3 个答案:

答案 0 :(得分:0)

查看source搜索"Inspected frame has gone"它可能会让您了解正在发生的事情。 这确实是一个很好的候选人。

void InspectorRuntimeAgent::getProperties(ErrorString* errorString, const String& objectId, const bool* const ownProperties, RefPtr<InspectorArray>* result)
{
    InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(objectId);
    if (injectedScript.hasNoValue()) {
        *errorString = "Inspected frame has gone";
    return;
    }
    injectedScript.getProperties(errorString, objectId, ownProperties ? *ownProperties : false, result);
}

您正在传递window.foo.bar作为const String&amp; OBJECTID。
我认为它无法找到它,因为你必须点击injectedScript.hasNoValue()

答案 1 :(得分:0)

重要的是要知道Runtime.evaluate accesses at the level of window,因此如果您想要访问window.document,则需要document作为表达。

这样做最终有效:

window.document.foo = "bar"

在请求中:

{
  :method => "Runtime.evaluate", 
  :params => {
    :expression => "document.foo"
  },
  "id" => 1
}

如果要访问对象属性等,可能需要将参数中的returnByValue设置为true

答案 2 :(得分:0)

Runtime.evaluateRuntime.callFunctionOn返回具有objectId字段的RemoteObject,以防表达式已评估为Object。如果您通过Runtime.getProperties枚举它们,将为对象的属性返回更多对象标识符。