无法访问从硒execute_script传递 API 的 Chrome 消息

unable to access chrome message passing API from selenium execute_script

本文关键字:API 传递 Chrome 消息 script 访问 execute      更新时间:2023-09-26

我需要从浏览器自动化脚本向chrome扩展程序发送一个值。我目前尝试这样做的方法是尝试从 selenium 调用 chrome.runtime.sendMessage 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)" 

问题: 知道我做错了什么吗?

我需要从浏览器向 chrome 扩展程序发送一个值 自动化脚本。我该怎么做?

运行这个时遇到类似的错误:(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.

这是因为您的测试页正在尝试与您的扩展程序进行通信,根据 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);
});

在清单中声明内容脚本:

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

在content_script.js:

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

希望对你有帮助

正如异常消息所说,Cannot call method 'sendMessage' of undefined .似乎chrome.runtime调用仅在 chrome 扩展程序的 contenxt 中调用,并且在 execute_script 中执行的代码只是在您的页面上下文中。

据我了解,从您的硒 python 代码中,您想将数据发送到谷歌浏览器扩展程序。这是不可能的。您没有权限,Chrome 也不允许您这样做。除非您将创建一些隐藏的 html 元素,例如任何 id = 'message' 的元素,并在数据属性中发送参数或作为元素的值。并在您的谷歌浏览器扩展中创建内容脚本,该脚本将在页面加载后注入到页面。内容脚本注入页面后,您可以通过给定的 ID 获取参数。

这个问题可能有多个解决方案。但我建议将内容脚本页面用于扩展,并使用内容脚本中的函数进行通信。由于内容脚本构成客户端部分,因此可以访问内容脚本中定义的函数,以便与扩展进行通信,而不会出现任何问题。如果这不适合您,请告诉我。