【问题标题】:unable to access chrome message passing API from selenium execute_script无法从 selenium execute_script 访问 chrome 消息传递 API
【发布时间】:2013-10-24 00:55:49
【问题描述】:

我需要从浏览器自动化脚本向 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 python google-chrome selenium


    【解决方案1】:

    运行时遇到类似错误:(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');
    });
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-03-24
            • 1970-01-01
            • 2022-08-15
            • 1970-01-01
            • 2020-08-26
            相关资源
            最近更新 更多