如何使用Chrome内容脚本自动执行网页交互和嵌套导航

时间:2013-09-18 17:38:58

标签: google-chrome google-chrome-extension

我正在尝试从C#应用程序中控制chrome。

我希望在我的C#应用​​程序和Chrome之间建立一个相当简单的API。

- Navigate to url
- Find HTML element based on some criteria (typically to be done via jQuery)
- Click on the selected element
- Repeat as needed

我的C#程序将管理多个执行此类工作的Chrome实例。

我尝试实施的解决方案是使用Chrome扩展程序“内容”脚本

这是我现在的Manifest.json:

{
    "name": "ScraperAPI",
    "manifest_version": 2,
    "version": "0.0.1",
    "content_scripts":  [
                {
                "matches": [ "<all_urls>" ],
                "js": [ "AutomationApi.js"],
                "run_at" : "document_start",
                "all_frames" : false
                }
    ],
    "permissions": [ "tabs", "http://*/*", "storage" ]
    "web_accessible_resources": [ "jQuery.min.v.2.0.3.map" ]
}

内容脚本使用WebSocket与我的C#应用​​程序进行通信

到目前为止,WebSocket非常适用于传递API请求(例如“导航”)和响应(例如“文档就绪”)。

我的扩展程序监听文档准备就绪并打开WebSocket到我的C#程序。      - 这个工作

我的问题是:

[1]如何在Chrome启动时自动启动内容脚本?     似乎在我在导航栏中手动输入URL之前,我的扩展名未加载

内容脚本如何识别它在chrome实例中第一次运行?

[2]如何跨页面加载维护内容脚本的一般状态。

特别是,C#程序使用内容脚本导航到URL,     找到一个特定的HTML元素,单击它,然后在“文档准备好”之后     想继续浏览并进一步点击页面。

不幸的是(对我来说),每次加载页面时,Chrome都会加载内容脚本的新实例。

==> I don't know how to have the script determine whether it is running for the first time or not.
    On the first time through it has to open a WebSocket to the C#. On subsequent loads in the same tab
    I want it to recognize that the WebSocket connection exists and continue using it.

    I tried to create a 'window.myApi' object to save data, but each page seems to get a new window object.

    I was going to try to use 'local storage' but that is shared between all local instances of all the scripts
    and a fresh instance of the content script does not know whether it is running for first time or not.

    By the way, when my content script opens a WebSocket to the C#, the C# responds with a unique id (GUID) so
    all further communications use this unique id in the messages.

    It would be great if a content script can tell if it has been assigned a unique id by the C# program.

    Is there an 'uber' window for the entire Chrome instance that I can latch onto?

我是否应该使用其他方法(不使用内容脚本)来自动化Chrome会话?

有没有一种方法来保存我错过的状态?

非常感谢任何帮助。

- 提前多多感谢 [大卫]

1 个答案:

答案 0 :(得分:0)

内容脚本的执行环境通常在导航时被破坏,因此您不能仅使用内容脚本建立永久套接字连接。 Chrome启动时会加载background page,并会在Chrome关闭之前生效。在那里,您可以拥有永久套接字连接,并存储您需要的任何状态。

对于与HTML文档的任何交互,您仍然需要使用内容脚本。您可以使用message passing通过后台页面在C#应用程序和内容脚本之间中继邮件。