aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/mozilla/add-ons/webextensions/api/tabs/executescript/index.html
blob: f78b8956dd1bb2626744236da5f7c4a8463758ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
---
title: tabs.executeScript()
slug: Mozilla/Add-ons/WebExtensions/API/tabs/executeScript
tags:
  - Chrome Extensions
  - Extensions
  - Plugins
  - WebExtensions
  - executeScript
  - tabs.executeScript()
translation_of: Mozilla/Add-ons/WebExtensions/API/tabs/executeScript
---
<div>{{AddonSidebar()}}</div>

<p>将 JavaScript 代码注入页面。</p>

<p>You can inject code into pages whose URL can be expressed using a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">match pattern</a>: meaning, its scheme must be one of "http", "https", "file", "ftp". To do this you must have the permission for the page's URL, either explicitly as a <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission</a>, or via the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission">activeTab permission</a>.</p>

<p>You can also inject code into pages packaged with your own extension:</p>

<pre class="brush: js">browser.tabs.create({url: "/my-page.html"}).then(() =&gt; {
  browser.tabs.executeScript({
    code: `console.log('location:', window.location.href);`
  });
});</pre>

<p>You don't need any special permissions to do this.</p>

<p>You <em>can't</em> inject code into any of the browser's built-in pages, such as about:debugging, about:addons, or the page that opens when you open a new empty tab.</p>

<p>The scripts you inject are called content scripts. <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">Learn more about content scripts</a>.</p>

<p>This is an asynchronous function that returns a <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox brush:js">var executing = browser.tabs.executeScript(
  tabId,                 // optional integer
  details                // object
)
</pre>

<h3 id="Parameters">Parameters</h3>

<dl>
 <dt><code>tabId</code> {{optional_inline}}</dt>
 <dd><code>integer</code>. The ID of the tab in which to run the script. Defaults to the active tab of the current window.</dd>
 <dt><code>details</code></dt>
 <dd>An object describing the script to run. It contains the following properties:</dd>
 <dd>
 <dl class="reference-values">
  <dt><code>allFrames</code> {{optional_inline}}</dt>
  <dd><code>boolean</code>. If <code>true</code>, the code will be injected into all frames of the current page. If <code>true</code> and <code>frameId</code> is set, then it will raise an error,  frameId and allFrames are mutually exclusive. If it is <code>false</code>, code is only injected into the top frame. Defaults to <code>false</code>.</dd>
  <dt><code>code</code> {{optional_inline}}</dt>
  <dd><code>string</code>. Code to inject, as a text string. <strong>Warning:</strong> Don’t use this property to interpolate untrusted data into JavaScript, as this could lead to a security issue.</dd>
  <dt><code>file</code> {{optional_inline}}</dt>
  <dd><code>string</code>. Path to a file containing the code to inject. In Firefox, relative URLs not starting at the extension root are resolved relative to the current page URL. In Chrome, these URLs are resolved relative to the extension's base URL. To work cross-browser, you can specify the path as a relative URL, starting at the extension's root, like this: <code>"/path/to/script.js"</code>.</dd>
  <dt><code>frameId</code> {{optional_inline}}</dt>
  <dd><code>integer</code>. The frame where the code should be injected. Defaults to <code>0</code> (the top-level frame).</dd>
  <dt><code>matchAboutBlank</code> {{optional_inline}}</dt>
  <dd><code>boolean</code>. If <code>true</code>, the code will be injected into embedded "about:blank" and "about:srcdoc" frames if your extension has access to their parent document. The code cannot be inserted in top-level about: frames. Defaults to <code>false</code>.</dd>
  <dt><code>runAt</code> {{optional_inline}}</dt>
  <dd>{{WebExtAPIRef('extensionTypes.RunAt')}}. The soonest that the code will be injected into the tab. Defaults to "document_idle".</dd>
 </dl>
 </dd>
</dl>

<h3 id="Return_value">Return value</h3>

<p>A <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> that will be fulfilled with an array of objects, representing the result of the script in every injected frame.</p>

<p>The result of the script is the last evaluated statement, which is similar to what would be output (the results, not any <code>console.log()</code> output) if you executed the script in the <a href="/en-US/docs/Tools/Web_Console">Web Console</a>. For example, consider a script like this:</p>

<pre class="brush: js">var foo='my result';foo;</pre>

<p>Here the results array will contain the the string "<code>my result</code>" as an element. The result values must be <a href="/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">structured clonable</a>.</p>

<p>If any error occurs the promise will be rejected with an error message.</p>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p>{{Compat("webextensions.api.tabs.executeScript")}}</p>

<h2 id="Examples">Examples</h2>

<p>This example executes a one-line code snippet in the currently active tab:</p>

<pre class="brush: js">function onExecuted(result) {
  console.log(`We made it green`);
}

function onError(error) {
  console.log(`Error: ${error}`);
}

var makeItGreen = 'document.body.style.border = "5px solid green"';

var executing = browser.tabs.executeScript({
  code: makeItGreen
});
executing.then(onExecuted, onError);</pre>

<p>This example executes a script from a file, packaged with the extension, called "content-script.js". The script is executed in the currently active tab. The script is executed in subframes as well as the main document:</p>

<pre class="brush: js">function onExecuted(result) {
  console.log(`We executed in all subframes`);
}

function onError(error) {
  console.log(`Error: ${error}`);
}

var executing = browser.tabs.executeScript({
  file: "/content-script.js",
  allFrames: true
});
executing.then(onExecuted, onError);</pre>

<p>This example executes a script from a file, packaged with the extension, called "content-script.js". The script is executed in the tab with an ID of 2:</p>

<pre class="brush: js">function onExecuted(result) {
  console.log(`We executed in tab 2`);
}

function onError(error) {
  console.log(`Error: ${error}`);
}

var executing = browser.tabs.executeScript(
  2, {
    file: "/content-script.js"
});
executing.then(onExecuted, onError);</pre>

<p>{{WebExtExamples}}</p>

<div class="note"><strong>Acknowledgements</strong>

<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/tabs#method-executeScript"><code>chrome.tabs</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json"><code>tabs.json</code></a> in the Chromium code.</p>
</div>

<div class="hidden">
<pre>// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</pre>
</div>