javascript - 无法从 selenium execute_script 访问 chrome 消息传递 API

标签 javascript python google-chrome selenium

我需要从浏览器自动化脚本向 chrome 扩展发送一个值。 我目前尝试的方式是尝试调用 chrome.runtime.sendMessage来自 selenium 的 API,用于将一些值传递给 chrome 扩展。 python代码是:

import os
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options



chrome_options = Options()
chrome_options.add_extension('/home/lurscher/plugin.crx')
browser = webdriver.Chrome(chrome_options=chrome_options)
browser.get(url)
browser.execute_script("chrome.runtime.sendMessage({someValue: "+str(args.value)+"}, function(response) { console.log('value sent. '+response)})")

我收到这个错误:

Traceback (most recent call last):
  File "tools/selenium/open_page.py", line 17, in <module>
    browser.execute_script("chrome.runtime.sendMessage({someValue: "+str(args.value)+"}, function(response) { console.log('value sent. '+response)})")
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 397, in execute_script
    {'script': script, 'args':converted_args})['value']
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 165, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 164, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: u"unknown error: Cannot call method 'sendMessage' of undefined\n  (Session info: chrome=28.0.1500.71)\n  (Driver info: chromedriver=2.1,platform=Linux 3.5.0-17-generic x86_64)" 

Question: Any idea what I'm doing wrong?

I need to send a value to the chrome extension from the browser automation script. How Do I Do It?

最佳答案

运行时遇到类似的错误:(JavaScript)

this.driver.executeScript(function () {
    chrome.runtime.sendMessage('start');
});
WebDriverError: unknown error: Cannot read property 'sendMessage' of undefined

在我看来,无论您是在开发扩展还是只是浏览网页,chrome.runtime 始终可用。 (打开一个隐身窗口并在控制台中评估它;它就在那里。)所以它必须与 WebDriver 有关。

根据我在互联网上收集到的信息,您必须额外配置您的驱动程序: https://groups.google.com/forum/#!topic/chromedriver-users/7wF9EHF2jxQ

options.excludeSwitches('test-type'); // this makes chrome.runtime available
builder.setChromeOptions(options);

然而这使得上述错误演变为:

WebDriverError: unknown error: Invalid arguments to connect.

那是因为您的测试页面正在尝试与您的扩展进行通信,除非您在 list 中声明该页面,否则根据 Chrome 规范这是不允许的。例如:

"externally_connectable": {
    "matches": [
    "http://localhost:8000/mytest.html”
    ]
}

但是,您现在必须在 sendMessage 调用中包含扩展 ID:

this.driver.executeScript(function () {
    chrome.runtime.sendMessage('kjnfjpehjfekjjhcgkodhnpfkoalhehl', 'start');
});

我觉得这有点尴尬。

我会根据 MGR 的建议推荐一些内容,即使用内容脚本来代理您的 sendMessage 调用,因为内容脚本对外部页面没有限制。

我所做的是从我的测试中触发一个事件,该事件将由内容脚本拾取,该脚本调用 sendMessage 函数:

在你的测试中:

this.driver.executeScript(function () {
    var event = document.createEvent('HTMLEvents');
    event.initEvent('extension-button-click', true, true);
    document.dispatchEvent(event);
});

在您的 list 中声明一个内容脚本:

"content_scripts": [
    { "matches": ["<all_urls>"], "js": ["content_script.js"] }
]

在 content_script.js 中:

document.addEventListener('extension-button-click', function () {
    chrome.runtime.sendMessage('start');
});

希望对你有帮助

关于javascript - 无法从 selenium execute_script 访问 chrome 消息传递 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394459/

相关文章:

javascript - 仅获取未隐藏的元素.. Jquery

python - Zeromq (pyzmq) ROUTER处理多个客户端的数据以及后续的超时处理

google-chrome - 在 Chromium 中使用 WebCrypto 生成 RSA key 对

css - 为什么 Chrome 中的图像宽度不超过 500px?

JavaScript boolean 运算不工作且循环出错

javascript - 为什么这没有在 MySQL 数据库中添加用户 ID?

javascript - 我真的需要使用 jQuery 检查元素是否存在吗?

python - 使用 Selenium 在动态表中搜索字符串

python - 提交前验证 WTForm

javascript - 如何检查选项卡加载失败