gpt4 book ai didi

javascript - selenium-webdriver 将函数数组作为参数传递给 executeScript

转载 作者:行者123 更新时间:2023-11-30 16:09:51 25 4
gpt4 key购买 nike

import webdriver from 'selenium-webdriver';

const driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();

driver.get('https://www.google.com');
let foo = function(rules) {
rules.forEach(rule => {
rule();
});
}
let bar = function() { return 'bar' };
let baz = function() { return 'baz' };
driver.executeScript(foo, [bar, baz]).then(function(result) {
console.log(result);
});

driver.quit();

它出错了

WebDriverError: unknown error: rule is not a function


let foo = function(rules) {
return rules;
// rules.forEach(rule => {
// rule();
// });
}
let bar = function() { return 'bar' };
let baz = function() { return 'baz' };
driver.executeScript(foo, [bar, baz]).then(function(result) {
console.log(result); // refer the log pasted below
});

看起来函数正在序列化为 string

[ 'function bar() {\n  return \'bar\';\n}',
'function baz() {\n return \'baz\';\n}' ]

任何关于如何将函数数组作为参数传递的指针都会有所帮助。

最佳答案

我找到了一个不同的解决方法,不使用 eval 明确地,但以类似的方式。

  1. 要注入(inject)的函数必须是namedfunction
  2. 注入(inject) function.toString()作为 <script> 的内容

    function foo(rules) {
    var result = [];
    rules.forEach(rule => {
    result.push(rule());
    });
    return result;
    }
    function bar() { return 'bar' };
    function baz() { return 'baz' };

    function inject(content) {
    var script = document.createElement('script');
    script.innerHTML = content;
    document.head.appendChild(script);
    }
    let script = `${bar.toString()} ${baz.toString()} ${foo.toString()}`;

    driver.executeScript(inject, script);
  3. 然后执行所需的函数为

    driver.executeScript('return foo([bar, baz])').then(function(result) {
    // use the result
    });

完整的例子

// example.js
import webdriver from 'selenium-webdriver';

const driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();

driver.get('https://www.google.com');

function foo(rules) {
var result = [];
rules.forEach(rule => {
result.push(rule());
});
return result;
}
function bar() { return 'bar' };
function baz() { return 'baz' };

function inject(content) {
var script = document.createElement('script');
script.innerHTML = content;
document.head.appendChild(script);
}
let script = `${bar.toString()} ${baz.toString()} ${foo.toString()}`;

driver.executeScript(inject, script);

driver.executeScript('return foo([bar, baz])').then(function(result) {
console.log(result);
});

driver.quit();

> babel-node example.js

[ 'bar', 'baz' ]

关于javascript - selenium-webdriver 将函数数组作为参数传递给 executeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com