Chrome扩展:消息传递

由于内容脚本在网页而不是扩展程序的环境中运行,它们通常需要某种方式与扩展程序的其余部分通信。例如,RSS 阅读器扩展程序可能使用内容脚本检测页面上是否存在 RSS 供稿,然后通知后台页面,为当前页面显示页面按钮图标。

扩展程序和内容脚本间的通信使用消息传递的方式。两边均可以监听另一边发来的消息,并通过同样的通道回应。消息可以包含任何有效的 JSON 对象(null、boolean、number、string、array 或 object)。对于一次性的请求有一个简单的 API,同时也有更复杂的 API,允许您通过长时间的连接与共享的上下文交换多个消息。另外您也可以向另一个扩展程序发送消息,只要您知道它的标识符,这将在跨扩展程序消息传递部分介绍。

如果您只需要向您的扩展程序的另一部分发送一个简单消息(以及可选地获得回应),您应该使用比较简单的 runtime.sendMessage 方法。这些方法允许您从内容脚本向扩展程序发送可通过 JSON 序列化的消息,可选的 callback 参数允许您在需要的时候从另一边处理回应。

如下列代码所示从内容脚本中发送请求:

从扩展程序向内容脚本发送请求与上面类似,唯一的区别是您需要指定发送至哪一个标签页。这一例子演示如何向选定标签页中的内容脚本发送消息。

在接收端,您需要设置一个 runtime.onMessage 事件监听器来处理消息。

注意: 如果多个页面都监听 onMessage 事件,对于某一次事件只有第一次调用 sendResponse() 能成功发出回应,所有其他回应将被忽略。

有时候需要长时间的对话,而不是一次请求和回应。在这种情况下,您可以使用runtime.connecttabs.connect 从您的内容脚本建立到扩展程序的长时间连接。建立的通道可以有一个可选的名称,让您区分不同类型的连接。

使用长时间连接的一种可能的情形为自动填充表单的扩展程序。对于一次登录操作,内容脚本可以连接到扩展程序页面,每次页面上的输入元素需要填写表单数据时向扩展程序发送消息。共享的连接允许扩展程序保留来自内容脚本的不同消息之间的状态联系。

建立连接时,两端都将获得一个 runtime.Port 对象,用来通过建立的连接发送和接收消息。

如下代码演示如何从内容脚本中建立连接,发送并监听消息:

为了处理传入连接,您需要设置一个 runtime.onConnect 事件监听器。这一步无论在内容脚本还是扩展程序页面中都是一样的。当您的扩展程序的另一部分调用 connect() 时,会产生这一事件,同时传递您可以通过建立的连接发送和接受消息的 runtime.Port 对象。如下代码演示如何回应传入连接:

您可能想知道连接何时关闭,例如您需要为每一个打开的端口单独保留状态。这种情况下您可以监听 runtime.Port.onDisconnect 事件,当连接的另一端调用 runtime.Port.disconnect 或包含该端口的页面已结束(例如标签页转到了另一个页面)时,对于每一个端口确保都会发生一次该事件。

除了在您的扩展程序的不同组成部分间发送消息以外,您也可以使用消息传递 API 与其他扩展程序通信。这样您可以提供一个公共的 API,让其他扩展程序使用。

监听传入的请求和连接与处理内部的消息类似,唯一的区别是您分别使用runtime.onMessageExternalruntime.onConnectExternal 事件。如下是分别处理这两个事件的例子:

同样,向另一个扩展程序发送消息与在您的扩展程序中发送消息类似,唯一的区别是您必须传递您需要与之通信的扩展程序的标识符。例如:

跨扩展程序消息传递类似,您的应用或扩展程序可以接受并响应来自普通网页的消息。要使用该特性,您必须首先在您的 manifest.json 中指定您希望与之通信的网站,例如:

这样会将消息传递 API 提供给所有匹配您指定的 URL 表达式的网页。URL 表达式必须至少包含一个二级域名,也就是说禁止使用类似于“*”、“*.com”、“*.co.uk”和“*.appspot.com”之类的主机名。在网页中,使用 runtime.sendMessageruntime.connect API 向指定应用或扩展程序发送消息。例如:

在您的应用或扩展程序中,您可以通过 runtime.onMessageExternalruntime.onConnectExternal API 监听来自网页的消息,与跨扩展程序消息传递类似。只有网页才能发起连接。如下是一个例子:

扩展程序可以与原生应用程序交换消息。支持该特性的原生应用程序必须注册一个了解如何与扩展程序通信的原生消息宿主,Chrome 浏览器将在单独的进程中启动宿主,并通过标准输入和标准输出流与之通信。

为了注册一个原生消息通信宿主,应用程序必须安装一个清单文件,定义原生消息通信宿主的配置。如下是这一清单文件的例子:

消息通信宿主清单文件包含如下字段:

名称 描述
name 原生消息通信宿主的名称,客户端需要将该字符串传递给runtime.connectNativeruntime.sendNativeMessage
description 应用程序的简短描述。
path 原生消息通信宿主的二进制文件路径。在 Linux 和 OSX 上必须使用绝对路径,在 Windows 上可以使用相对于清单文件所在目录的路径。
type 与原生消息通信宿主交流时所使用的接口类型。目前该参数只有一种可能的值:stdio,它表示 Chrome 浏览器应该使用stdin(标准输入)和 stdout(标准输出)与宿主通信。
allowed_origins 允许访问原生消息通信宿主的扩展程序列表。

清单文件的类型取决与平台:

Windows:
清单文件可以在文件系统中的任意位置,应用程序的安装程序必须创建如下注册表键HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.my_company.my_applicationHKEY_CURRENT_USER\SOFTWARE\Google\Chrome\NativeMessagingHosts\com.my_company.my_application,并将键的默认值设置为清单文件的完整路径。
OSX:
清单文件必须位于/Library/Google/Chrome/NativeMessagingHosts/com.my_company.my_application.json,对于在用户级别上安装的应用程序则是 ~/Library/Application Support/Google/Chrome/NativeMessagingHosts/com.my_company.my_application.json
Linux:
清单文件必须位于 /etc/opt/chrome/native-messaging-hosts/com.my_company.my_application.json,对于在用户级别上安装的应用程序则是 ~/.config/google-chrome/NativeMessagingHosts/com.my_company.my_application.json

Chrome 浏览器在单独的进程中启动每一个原生消息通信宿主,并使用标准输入(stdin)与标准输出(stdout)与之通信。向两个方向发送消息时使用相同的格式:每一条消息使用 JSON 序列化,以 UTF-8 编码,并在前面附加 32 位的消息长度(使用本机字节顺序)。

使用 runtime.connectNative 创建消息传递端口时,Chrome 浏览器会启动原生消息传递宿主进程,并让它一直运行,直到端口释放。如果消息是使用 runtime.sendNativeMessage 发送,没有创建消息传递端口,Chrome 浏览器会为每一条消息创建一个新的原生消息传递宿主进程。在这种情况下,宿主进程产生的第一条消息作为原始请求的响应处理,也就是说,Chrome 浏览器会将它传递给调用 runtime.sendNativeMessage 时指定的回调函数,而原生消息传递宿主产生的所有其他消息则会忽略。

向原生应用程序发送和接收消息类似与跨扩展程序消息传递,主要的区别是用runtime.connectNative 代替 runtime.connect,用 runtime.sendNativeMessage 代替 runtime.sendMessage

以下例子创建一个 runtime.Port 对象,连接到原生消息通信宿主com.my_company.my_application,开始监听来自该端口的消息,并发送一条消息:

runtime.sendNativeMessage 可以用来向原生应用程序发送消息,而不用创建端口。例如:

当您从内容脚本或另一个扩展程序接收消息时,您的后台网页应该小心,以免遭到跨站脚本攻击。特别地,避免使用下面这些危险的 API:

您应该首选不运行脚本的更安全的API:

您可以在 examples/api/messaging -->目录中找到使用消息通信的简单例子,examples/api/nativeMessaging 包含使用原生消息通信的示例应用程序,另外请参见contentscript_xhr 例子,在这个例子中内容脚本与所属扩展程序交换消息,以便扩展程序可以代表内容脚本发出跨站请求。有关更多例子以及查看源代码的帮助,请参见示例

参考链接


消息传递

Chrome插件(Extensions)开发攻略

本文将从个人经验出发,讲述为什么需要Chrome插件,如何开发,如何调试,到哪里找资料,会遇到怎样的问题以及如何解决等,同时给出一个个人认为的比较典型的例子——获取网页内容,和服务器交互,再把信息反馈给用户。OK,准备开始吧,我尽量把文章写得好看点,以免读者打瞌睡。

目录

  1. 为什么需要
  2. 为什么是Chrome
  3. 需要准备什么
  4. 如何开始
  5. Page Action
  6. Chrome插件结构
  7. 学习资料
  8. 我的例子
  9. 调试
  10. 总结

继续阅读Chrome插件(Extensions)开发攻略

Chrome Extension:Content Scripts

Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

Here are some examples of what content scripts can do:

  • Find unlinked URLs in web pages and convert them into hyperlinks
  • Increase the font size to make text more legible
  • Find and process microformat data in the DOM

However, content scripts have some limitations. They cannot:

These limitations aren't as bad as they sound. Content scripts can indirectly use the chrome.* APIs, get access to extension data, and request extension actions by exchanging messages with their parent extension. Content scripts can also make cross-site XMLHttpRequests to the same sites as their parent extensions, and they cancommunicate with web pages using the shared DOM. For more insight into what content scripts can and can't do, learn about the execution environment.

If your content script's code should always be injected, register it in the extension manifest using the content_scripts field, as in the following example.

{
"name": "My extension",
...
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mystyles.css"],
"js": ["jquery.js", "myscript.js"]

}

],

...

}

If you want to inject the code only sometimes, use the permissions field instead, as described in Programmatic injection.

{
"name": "My extension",
...
"permissions": [
"tabs", "http://www.google.com/*"
],

...

}

Using the content_scripts field, an extension can insert multiple content scripts into a page; each of these content scripts can have multiple JavaScript and CSS files. Each item in the content_scripts array can have the following properties:

Name Type Description
matches array of strings Required. Specifies which pages this content script will be injected into. See Match Patterns for more details on the syntax of these strings and Match patterns and globs for information on how to exclude URLs.
exclude_matches array of strings Optional. Excludes pages that this content script would otherwise be injected into. See Match Patternsfor more details on the syntax of these strings and Match patterns and globs for information on how to exclude URLs.
match_about_blank boolean Optional. Whether to insert the content script on about:blank and about:srcdoc. Content scripts will only be injected on pages when their inherit URL is matched by one of the declared patterns in thematches field. The inherit URL is the URL of the document that created the frame or window.
Content scripts cannot be inserted in sandboxed frames.Defaults to false.
css array of strings Optional. The list of CSS files to be injected into matching pages. These are injected in the order they appear in this array, before any DOM is constructed or displayed for the page.
js array of strings Optional. The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array.
run_at string Optional. Controls when the files in js are injected. Can be "document_start", "document_end", or "document_idle". Defaults to "document_idle".

In the case of "document_start", the files are injected after any files from css, but before any other DOM is constructed or any other script is run.

In the case of "document_end", the files are injected immediately after the DOM is complete, but before subresources like images and frames have loaded.

In the case of "document_idle", the browser chooses a time to inject scripts between "document_end" and immediately after the window.onload event fires. The exact moment of injection depends on how complex the document is and how long it is taking to load, and is optimized for page load speed.

Note: With "document_idle", content scripts may not necessarily receive the window.onload event, because they may run after it has already fired. In most cases, listening for the onload event is unnecessary for content scripts running at "document_idle" because they are guaranteed to run after the DOM is complete. If your script definitely needs to run after window.onload, you can check if onload has already fired by using the document.readyState property.

all_frames boolean Optional. Controls whether the content script runs in all frames of the matching page, or only the top frame.

Defaults to false, meaning that only the top frame is matched.

include_globs array of string Optional. Applied after matches to include only those URLs that also match this glob. Intended to emulate the @include Greasemonkey keyword. See Match patterns and globs below for more details.
exclude_globs array of string Optional. Applied after matches to exclude URLs that match this glob. Intended to emulate the @excludeGreasemonkey keyword. See Match patterns and globs below for more details.

The content script will be injected into a page if its URL matches any matches pattern and any include_globspattern, as long as the URL doesn't also match an exclude_matches or exclude_globs pattern. Because the matches property is required, exclude_matchesinclude_globs, and exclude_globs can only be used to limit which pages will be affected.

For example, assume matches is ["http://*.nytimes.com/*"]:

  • If exclude_matches is ["*://*/*business*"], then the content script would be injected into "http://www.nytimes.com/health" but not into "http://www.nytimes.com/business".
  • If include_globs is ["*nytimes.com/???s/*"], then the content script would be injected into "http:/www.nytimes.com/arts/index.html" and "http://www.nytimes.com/jobs/index.html" but not into "http://www.nytimes.com/sports/index.html".
  • If exclude_globs is ["*science*"], then the content script would be injected into "http://www.nytimes.com" but not into "http://science.nytimes.com" or "http://www.nytimes.com/science".

Glob properties follow a different, more flexible syntax than match patterns. Acceptable glob strings are URLs that may contain "wildcard" asterisks and question marks. The asterisk (*) matches any string of any length (including the empty string); the question mark (?) matches any single character.

For example, the glob "http://???.example.com/foo/*" matches any of the following:

  • "http://www.example.com/foo/bar"
  • "http://the.example.com/foo/"

However, it does not match the following:

  • "http://my.example.com/foo/bar"
  • "http://example.com/foo/"
  • "http://www.example.com/foo"

Inserting code into a page programmatically is useful when your JavaScript or CSS code shouldn't be injected into every single page that matches the pattern — for example, if you want a script to run only when the user clicks a browser action's icon.

To insert code into a page, your extension must have cross-origin permissions for the page. It also must be able to use the chrome.tabs module. You can get both kinds of permission using the manifest file'spermissions field.

Once you have permissions set up, you can inject JavaScript into a page by calling tabs.executeScript. To inject CSS, use tabs.insertCSS.

The following code (from the make_page_red example) reacts to a user click by inserting JavaScript into the current tab's page and executing the script.

When the browser is displaying an HTTP page and the user clicks this extension's browser action, the extension sets the page's bgcolor property to 'red'. The result, unless the page has CSS that sets the background color, is that the page turns red.

Usually, instead of inserting code directly (as in the previous sample), you put the code in a file. You inject the file's contents like this:

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

For example, consider this simple page:

Now, suppose this content script was injected into hello.html:

Now, if the button is pressed, you will see both greetings.

Isolated worlds allow each content script to make changes to its JavaScript environment without worrying about conflicting with the page or with other content scripts. For example, a content script could include JQuery v1 and the page could include JQuery v2, and they wouldn't conflict with each other.

Another important benefit of isolated worlds is that they completely separate the JavaScript on the page from the JavaScript in extensions. This allows us to offer extra functionality to content scripts that should not be accessible from web pages without worrying about web pages accessing it.

It's worth noting what happens with JavaScript objects that are shared by the page and the extension - for example, the window.onload event. Each isolated world sees its own version of the object. Assigning to the object affects your independent copy of the object. For example, both the page and extension can assign to window.onload, but neither one can read the other's event handler. The event handlers are called in the order in which they were assigned.

Although the execution environments of content scripts and the pages that host them are isolated from each other, they share access to the page's DOM. If the page wishes to communicate with the content script (or with the extension via the content script), it must do so through the shared DOM.

An example can be accomplished using window.postMessage (or window.webkitPostMessage for Transferable objects):

In the above example, example.html (which is not a part of the extension) posts messages to itself, which are intercepted and inspected by the content script, and then posted to the extension process. In this way, the page establishes a line of communication to the extension process. The reverse is possible through similar means.

When writing a content script, you should be aware of two security issues. First, be careful not to introduce security vulnerabilities into the web site your content script is injected into. For example, if your content script receives content from another web site (for example, by making an XMLHttpRequest), be careful to filter that content for cross-site scripting attacks before injecting the content into the current page. For example, prefer to inject content via innerText rather than innerHTML. Be especially careful when retrieving HTTP content on an HTTPS page because the HTTP content might have been corrupted by a network "man-in-the-middle" if the user is on a hostile network.

Second, although running your content script in an isolated world provides some protection from the web page, a malicious web page might still be able to attack your content script if you use content from the web page indiscriminately. For example, the following patterns are dangerous:

Instead, prefer safer APIs that do not run scripts:

Get the URL of an extension's file using chrome.extension.getURL(). You can use the result just like you would any other URL, as the following code shows.

//Code for displaying <extensionDir>/images/myimage.png:
var imgURL = chrome.extension.getURL("images/myimage.png");
document.getElementById("someImage").src = imgURL;

You can find many examples that use content scripts. A simple example of communication via messages is in the Message Timer. See Page Redder and Email This Page for examples of programmatic injection.

The following videos discuss concepts that are important for content scripts. The first video describes content scripts and isolated worlds.

The next video describes message passing, featuring an example of a content script sending a request to its parent extension.

macOS High Sierra下使用brew安装支持x265的ffmpeg以及转码

使用

安装ffmpeg默认是不支持x265

使用

重新安装即可。

一般直接的H265数据流(比如从摄像头抓取的H265裸数据流保存的文件),是没办法在MacOS上直接播放的,必须进行转码。简单的转码命令如下:

参考链接


Chrome Extension:Debugging

This tutorial introduces you to using Google Chrome's built-in Developer Tools to interactively debug an extension.

View extension information

To follow this tutorial, you need the Hello World extension that was featured inGetting Started. In this section, you'll load the extension and take a look at its information in the Extensions page.

  1. Load the Hello World extension if it isn't already running. If the extension is running, you'll see the Hello World icon  to the right of your browser's address bar.If the Hello World extension isn't already running, find the extension files and load them. If you don't have a handy copy of the files, extract them from this ZIP file. See Getting Started if you need instructions for loading the extension.
  2. Go to the Extensions page (chrome://extensions), and make sure the page is in Developer mode.
  3. Look at the Hello World extension's information on that page. You can see details such as the extension's name, description, and ID.

Inspect the popup

As long as your browser is in Developer mode, it's easy to inspect popups.

  1. Go to the Extensions page (chrome://extensions), and make sure Developer mode is still enabled. The Extensions page doesn't need to be open for the following to work. The browser remembers the setting, even when the page isn't shown.
  2. Right-click the Hello World icon  and choose the Inspect popup menu item. The popup appears, and a Developer Tools window like the following should display the code for popup.html.The popup remains open as long as the Developer Tools window does.
  3. If the Scripts button isn't already selected, click it.
  4. Click the console button (second from left, at the bottom of the Developer Tools window) so that you can see both the code and the console.

Use the debugger

In this section, you'll follow the execution of the popup page as it adds images to itself.

    1. Set a breakpoint inside the image-adding loop by searching for the string img.src and clicking the number of the line where it occurs (for example, 37):
    2. Make sure you can see the popup.html tab. It should show 20 "hello world" images.
    3. At the console prompt, reload the popup page by entering location.reload(true):

      The popup page goes blank as it begins to reload, and its execution stops at line 37.
    4. In the upper right part of the tools window, you should see the local scope variables. This section shows the current values of all variables in the current scope. For example, in the following screenshot the value of i is 0, and photos is a node list that contains at least a few elements. (In fact, it contains 20 elements at indexes 0 through 19, each one representing a photo.)
    5. Click the play/pause button (near the top right of the Developer Tools window) to go through the image-processing loop a single time. Each time you click that button, the value of i increments and another icon appears in the popup page. For example, when i is 10, the popup page looks something like this:

  1. Use the buttons next to the play/pause button to step over, into, and out of function calls. To let the page finish loading, click line 37 to disable the breakpoint, and then press play/pause to continue execution.

Summary

This tutorial demonstrated some techniques you can use to debug your extensions:

  • Find your extension's ID and links to its pages in the Extensions page (chrome://extensions).
  • View hard-to-reach pages (and any other file in your extension) using chrome-extension://extensionId/filename.
  • Use Developer Tools to inspect and step through a page's JavaScript code.
  • Reload the currently inspected page from the console using location.reload(true).

Now what?

Now that you've been introduced to debugging, here are suggestions for what to do next:

  • Watch the extensions video Developing and Debugging.
  • Try installing and inspecting other extensions, such as the samples.
  • Try using widely available debugging APIs such as console.log() and console.error() in your extension's JavaScript code. Example: console.log("Hello, world!")
  • Follow the Developer Tools tutorial, explore the Developer Tools site, and watch some video tutorials.

For more ideas, see the Now what? section of Getting Started.

CMake如何编译CUDA(.cu)源文件

现在的项目,如果需要用到计算加速,NvidiaCUDA往往是首选。那么如何在CMake中编译写好的CUDA源代码,可以参考如下。

首先使用FIND_PACKAGE找到已经安装的CUDA,此时需要配置的环境变量等,应该已经自动配置完成了

接下来,使用CUDA_ADD_LIBRARY取代原来的ADD_LIBRARY,如下:

如果是可执行程序,请使用CUDA_ADD_EXECUTABLE取代ADD_EXECUTABLE

参考链接


CMake: how to add cuda to existing project

Getting Started: Building a Chrome Extension

Extensions allow you to add functionality to Chrome without diving deeply into native code. You can create new extensions for Chrome with those core technologies that you're already familiar with from web development: HTML, CSS, and JavaScript. If you've ever built a web page, you should feel right at home with extensions pretty quickly; we'll put that to the test right now by walking through the construction of a simple extension that will allow the user to change the background color of the current webpage.

继续阅读Getting Started: Building a Chrome Extension