💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 背景页 扩展常常用一个单独的长时间运行的脚本来管理一些任务或者状态。 Background pages to the rescue. 如同 [architecture overview](overview.html#arch) 的解释。背景页是一个运行在扩展进程中的HTML页面。它在你的扩展的整个生命周期都存在,同时,在同一时间只有一个实例处于活动状态。 在一个有背景页的典型扩展中,用户界面(比如,浏览器行为或者页面行为和任何选项页)是由沉默视图实现的。当视图需要一些状态,它从背景页获取该状态。当背景页发现了状态改变,它会通知视图进行更新。 ### 清单 请在[扩展清单](manifest.html)中注册背景页。一般,背景页不需要任何HTML,仅仅需要js文件,比如: ``` { "name": "My extension", ... **"background": { "scripts": ["background.js"] }**, ... } ``` 浏览器的扩展系统会自动根据上面`scripts`字段指定的所有js文件自动生成背景页。 如果您的确需要自己的背景页,可以使用`page`字段,比如: ``` { "name": "My extension", ... **"background": { "page": "background.html" }**, ... } ``` 如果你需要浏览器更早启动 — 例如,你想显示通知 — 那么,你也许也希望指定["background"权限](manifest.html#permissions_)。 ### 细节 可以用类似于帧之间通讯的方式,直接使用脚本调用在一个扩展的多个页面之间进行通讯。[`chrome.extension.getViews()`](extension.html#method-getViews) 方法会返回属于你的扩展的每个活动页面的窗口对象列表,而[`chrome.extension.getBackgroundPage()`](extension.html#method-getBackgroundPage) 方法返回背景页。 ### 范例 下面的代码片段演示了扩展如何在背景页中与其他页面交互。同时也展示如何使用背景页来处理事件,如用户点击。 例子中的扩展有一个背景页,多个由image.html创建的view页面。(通过[`chrome.tabs.create()`](tabs.html#method-create))。 ``` _//In background.js:_ // React when a browser action's icon is clicked. chrome.browserAction.onClicked.addListener(function(tab) { var viewTabUrl = chrome.extension.getURL('image.html'); var imageUrl = _/* an image's URL */_; // Look through all the pages in this extension to find one we can use. var views = chrome.extension.getViews(); for (var i = 0; i < views.length; i++) { var view = views[i]; // If this view has the right URL and hasn't been used yet... if (view.location.href == viewTabUrl && !view.imageAlreadySet) { // ...call one of its functions and set a property. view.setImageUrl(imageUrl); view.imageAlreadySet = true; break; // we're done } } }); _//In image.html:_ <html> <script> function setImageUrl(url) { document.getElementById('target').src = url; } </script> <body> <p> Image here: </p> <img id="target" src="white.png" width="640" height="480"> </body> </html> ```