tabs.insertCSS()
向一个页面注入 CSS
使用该 API 前你必须拥有目标页面的权限,可以是 主机权限, 或者使用 activeTab 权限.
你只能向符合 match pattern 的网页注入 CSS: 其形式必定是 "http", "https", "file", "ftp" 之一。你不能向任何浏览器内置页面注入 CSS,比如 about:debugging, about:addons, 或者你打开的一个新的空白页。
当再次调用tabs.removeCSS()
(en-US) 时,已经注入的 CSS 可能会被清除。
这是一个返回Promise
的异步函数。
Syntax
js
var inserting = browser.tabs.insertCSS(
tabId, // optional integer
details, // extensionTypes.InjectDetails
);
参数
tabId
可选-
integer
,将要注入 css 的标签 ID。默认为当前窗口的活动标签。 details
-
extensionTypes.InjectDetails
(en-US). 对注入的描述,包含以下属性: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
(en-US). 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
示例
下面例子将通过字符串变量形式向当前活动标签注入一段 CSS 代码
js
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 中。
js
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.