向一个页面注入CSS
使用该API前你必须拥有目标页面的权限, 可以是 主机权限, 或者使用 activeTab 权限.
你只能向符合 match pattern 的网页注入CSS: 其形式必定是 "http", "https", "file", "ftp" 之一. 你不能向任何浏览器内置页面注入CSS, 比如 about:debugging, about:addons, 或者你打开的一个新的空白页。
当再次调用tabs.removeCSS()
时,已经注入的CSS可能会被清除。
这是一个返回Promise
的异步函数。
Syntax
var inserting = browser.tabs.insertCSS(
tabId, // optional integer
details // extensionTypes.InjectDetails
)
参数
tabId
可选integer,
将要注入css的标签ID。默认为当前窗口的活动标签。details
extensionTypes.InjectDetails
. 对注入的描述,包含以下属性:-
allFrames
可选boolean
. 如果为真,该CSS会被注入到该页面的所有框架,如果为假,Css只会注入到最顶层框架,默认为假。code
可选string
. 将要注入的代码。file
可选string
. 包含将要注入代码的文件路径,在Firefox中,相对URLs 决定于当前页面的URL,在Chrome中,决定于扩展的基础URL。为了跨浏览器工作,你应该使用一个从扩展根目录开始的绝对路径,比如 :"/path/to/stylesheet.css"
.frameId
可选integer
. CSS应该被注入的框架. 默认为0
(顶层框架).matchAboutBlank
可选boolean
. Iftrue
, the code will be injected into embedded "about:blank" and "about:srcdoc" frames if your add-on has access to their parent document. The code cannot be inserted in top-level about: frames. Defaults tofalse
.runAt
可选extensionTypes.RunAt
. The soonest that the code will be injected into the tab. Defaults to "document_idle".
Return value
Promise
将会在CSS成功注入时 被填充,如果有任何错误发生,promise将会被注入一个错误消息。
Browser compatibility
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
例子
下面例子将通过字符串变量形式向当前活动标签注入一段CSS代码
var css = "body { border: 20px dotted pink; }";
browser.browserAction.onClicked.addListener(() => {
function onError(error) {
console.log(`Error: ${error}`);
}
var insertingCSS = browser.tabs.insertCSS({code: css});
insertingCSS.then(null, onError);
});
下面例子将以通过加载文件形式向页面注入CSS。CSS被注入在ID为2的tab中。
browser.browserAction.onClicked.addListener(() => {
function onError(error) {
console.log(`Error: ${error}`);
}
var insertingCSS = browser.tabs.insertCSS(2, {file: "content-style.css"});
insertingCSS.then(null, onError);
});
Example extensions
本页 API 以谷歌 Chromium的 chrome.tabs
API为基础. 该篇文档由Chromium 代码 tabs.json
衍变而来.
Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.