美文网首页
chrome浏览器extension的架构

chrome浏览器extension的架构

作者: 9b559869875b | 来源:发表于2017-11-15 12:40 被阅读15次

1. The background page

很多extension都会包含一个background page ,这是个隐藏的页面,包含了主要的逻辑

如果需要跟extension项目以外的网页(用户载入的)打交道,那就必须使用content script.

Background pages defined by background.html can include JavaScript code that controls the behavior of the extension. 有2种: persistent background pages, and event pages

Persistent background pages 是一直开着的,. Event pages 只在需要时候才开。

除非你确信一直要运行background page的代码,不然为了用户的性能,优先选择 event page.

2. UI 界面pages

2.1 popup: 

2.2 options page : lets users customize how the extension works

2.3 override page

2.4 tabs.create or window.open() to display any other HTML files that are in the extension.

同一个extension里的HTML pages对彼此的 DOMs 有完全的访问权限,它们也可以调用彼此的函数

 the popup can invoke functions on the background page.

3. Content scripts

如果要和web pages互动,就得用content script

content script 是在已经载入浏览器的页面里执行的一些javascript,把它看做载入页面的一部分,而不是看成打包它的extension的一部分。

Content scripts 可以读取 browser visit 的网页的详细信息, 它可以改变网页。以下示意图,

 content script 可以读写 displayed web page的 DOM, 然而,重要的事情说三遍,它不能修改扩展里的 background page,它不能修改扩展里的 background page,它不能修改extension里的 background page

那它是不是跟extension里的其它页面无法沟通了呢,非也。它可以通过 exchange messages, 如下的箭头所示. 

例如一个content script 当它在浏览器页面找到一个RSS feed时候可以send a message ,

一个 background page 可以发一个消息请求 content script 改变浏览器页面的样貌

更多关于content script的参考文档 

https://developer.chrome.com/extensions/content_scripts

content script可以做什么事儿?这儿有几个例子:

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


content script不是万能的,它有一些限制,

比如它只能使用部分的chrome.* APIs

extension(getURL,inIncognitoContext,lastError,onRequest,sendRequest)

i18n

runtime(connect,getManifest,getURL,id,onConnect,onMessage,sendMessage)

storage

它不能使用 扩展页面定义的变量,函数

不能使用 web pages or other content scripts 定义的变量,函数

看起来很糟糕?实则不然. 

虽然不能直接使用,但Content scripts 可以间接地使用  chrome.* APIs 啊!

它 可以访问extension data, 可以通过和extension 交换message 来请求extension actions(扩展页面定义的函数) 。

它也可以向和它 parent extensions一样的站点发起 cross-site XMLHttpRequests , and 他们可以和 web pages 使用shared DOM通讯.

如果想更全面地了解content script能做什么,不能做什么 learn about the execution environment.

相关文章

网友评论

      本文标题:chrome浏览器extension的架构

      本文链接:https://www.haomeiwen.com/subject/oqecvxtx.html