简体   繁体   English

如何使用 chrome.devtools.inspectedWindow.eval 从执行的脚本中返回值

[英]How to return value from executed script with chrome.devtools.inspectedWindow.eval

I'm trying to execute some script inside webpage from devtool panel using chrome.devtools.inspectedWindow.eval , the code is working fine but can't figure out how to return response to callback.我正在尝试使用chrome.devtools.inspectedWindow.eval从 devtool 面板执行网页内的一些脚本,代码工作正常,但无法弄清楚如何返回对回调的响应。 I am grateful for your support.我很感谢你的支持。

Executed script执行的脚本

const someScript = function () {
    alert("from panel")
    return 123
    // i can't return
}

Devtool开发工具

Chrome.devtools.inspectedWindow.eval(
//this regex convert function body to string
    someScript.toString().replace(/^function\s*\S+\s*\([^)]*\)\s*\{|\}$/g, ""),
       function (result, isException) {
           if (isException) {
               //exception always fire
               console.log("Result not received");
           } else {
               console.log("Selected element: " + result);
       }
});

The last evaluated expression of the script is returned to the callback.脚本的最后一个计算表达式返回给回调。

Assuming the function returns a value (your function does), all you need is to add some parentheses to call the function as an IIFE, no need to extract the function's body.假设 function 返回一个值(您的 function 确实如此),您只需添加一些括号来调用 function 即可,无需将函数体提取为 II。

const someFunc = function () {
  return 123;
};

chrome.devtools.inspectedWindow.eval(`(${someFunc})()`, (res, err) => {
  if (err) {
    console.warn('Error', err);
  } else {
    console.log('Result', res);
  }
});

Notes:笔记:

  • Only JSON-compatible types are supported (string, number, boolean, null, and arrays/objects that consist of these types).仅支持 JSON 兼容类型(字符串、数字、boolean、null 以及由这些类型组成的数组/对象)。
  • Your devtools panel has its own console, which you can open by right-clicking inside your panel to show the context menu and choosing "Inspect" there.您的 devtools 面板有自己的控制台,您可以通过在面板内部右键单击以显示上下文菜单并在此处选择“检查”来打开该控制台。
  • Use a comma , insead of + in console.log because the latter doesn't work with arrays/objects.在 console.log 中使用逗号,而不是+ ,因为后者不适用于数组/对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM