[英]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:笔记:
,
insead of +
in console.log because the latter doesn't work with arrays/objects.在 console.log 中使用逗号,
而不是+
,因为后者不适用于数组/对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.