summaryrefslogtreecommitdiffstats
path: root/dom/events/test/clipboard/browser_navigator_clipboard_contextmenu_suppression.js
blob: 97066cd2eb799eb8e58c9b9f7491730083adb922 (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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* -*- Mode: JavaScript; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";
requestLongerTimeout(2);

const kBaseUrlForContent = getRootDirectory(gTestPath).replace(
  "chrome://mochitests/content",
  "https://example.com"
);
const kContentFileName = "file_toplevel.html";
const kContentFileUrl = kBaseUrlForContent + kContentFileName;
const kIsMac = navigator.platform.indexOf("Mac") > -1;

async function waitForPasteContextMenu() {
  await waitForPasteMenuPopupEvent("shown");
  let pasteButton = document.getElementById(kPasteMenuItemId);
  info("Wait for paste button enabled");
  await BrowserTestUtils.waitForMutationCondition(
    pasteButton,
    { attributeFilter: ["disabled"] },
    () => !pasteButton.disabled,
    "Wait for paste button enabled"
  );
}

async function readText(aBrowser) {
  return SpecialPowers.spawn(aBrowser, [], async () => {
    content.document.notifyUserGestureActivation();
    return content.eval(`navigator.clipboard.readText();`);
  });
}

function testPasteContextMenuSuppression(aWriteFun, aMsg) {
  add_task(async function test_context_menu_suppression_sameorigin() {
    await BrowserTestUtils.withNewTab(
      kContentFileUrl,
      async function (browser) {
        info(`Write data by ${aMsg}`);
        let clipboardText = await aWriteFun(browser);

        info("Test read from same-origin frame");
        let listener = function (e) {
          if (e.target.getAttribute("id") == kPasteMenuPopupId) {
            ok(false, "paste contextmenu should not be shown");
          }
        };
        document.addEventListener("popupshown", listener);
        is(
          await readText(browser.browsingContext.children[0]),
          clipboardText,
          "read should just be resolved without paste contextmenu shown"
        );
        document.removeEventListener("popupshown", listener);
      }
    );
  });

  add_task(async function test_context_menu_suppression_crossorigin() {
    await BrowserTestUtils.withNewTab(
      kContentFileUrl,
      async function (browser) {
        info(`Write data by ${aMsg}`);
        let clipboardText = await aWriteFun(browser);

        info("Test read from cross-origin frame");
        let pasteButtonIsShown = waitForPasteContextMenu();
        let readTextRequest = readText(browser.browsingContext.children[1]);
        await pasteButtonIsShown;

        info("Click paste button, request should be resolved");
        await promiseClickPasteButton();
        is(await readTextRequest, clipboardText, "Request should be resolved");
      }
    );
  });

  add_task(async function test_context_menu_suppression_multiple() {
    await BrowserTestUtils.withNewTab(
      kContentFileUrl,
      async function (browser) {
        info(`Write data by ${aMsg}`);
        let clipboardText = await aWriteFun(browser);

        info("Test read from cross-origin frame");
        let pasteButtonIsShown = waitForPasteContextMenu();
        let readTextRequest1 = readText(browser.browsingContext.children[1]);
        await pasteButtonIsShown;

        info(
          "Test read from same-origin frame before paste contextmenu is closed"
        );
        is(
          await readText(browser.browsingContext.children[0]),
          clipboardText,
          "read from same-origin should just be resolved without showing paste contextmenu shown"
        );

        info("Dismiss paste button, cross-origin request should be rejected");
        await promiseDismissPasteButton();
        await Assert.rejects(
          readTextRequest1,
          /NotAllowedError/,
          "cross-origin request should be rejected"
        );
      }
    );
  });
}

add_setup(async function () {
  await SpecialPowers.pushPrefEnv({
    set: [
      ["dom.events.asyncClipboard.readText", true],
      ["dom.events.asyncClipboard.clipboardItem", true],
      ["test.events.async.enabled", true],
      // Avoid paste button delay enabling making test too long.
      ["security.dialog_enable_delay", 0],
    ],
  });
});

testPasteContextMenuSuppression(async aBrowser => {
  const clipboardText = "X" + Math.random();
  await SpecialPowers.spawn(aBrowser, [clipboardText], async text => {
    content.document.notifyUserGestureActivation();
    return content.eval(`navigator.clipboard.writeText("${text}");`);
  });
  return clipboardText;
}, "clipboard.writeText()");

testPasteContextMenuSuppression(async aBrowser => {
  const clipboardText = "X" + Math.random();
  await SpecialPowers.spawn(aBrowser, [clipboardText], async text => {
    content.document.notifyUserGestureActivation();
    return content.eval(`
      const itemInput = new ClipboardItem({["text/plain"]: "${text}"});
      navigator.clipboard.write([itemInput]);
    `);
  });
  return clipboardText;
}, "clipboard.write()");

testPasteContextMenuSuppression(async aBrowser => {
  const clipboardText = "X" + Math.random();
  await SpecialPowers.spawn(aBrowser, [clipboardText], async text => {
    let div = content.document.createElement("div");
    div.innerText = text;
    content.document.documentElement.appendChild(div);
    // select text
    content
      .getSelection()
      .setBaseAndExtent(div.firstChild, text.length, div.firstChild, 0);
  });
  // trigger keyboard shortcut to copy.
  await EventUtils.synthesizeAndWaitKey(
    "c",
    kIsMac ? { accelKey: true } : { ctrlKey: true }
  );
  return clipboardText;
}, "keyboard shortcut");

testPasteContextMenuSuppression(async aBrowser => {
  const clipboardText = "X" + Math.random();
  await SpecialPowers.spawn(aBrowser, [clipboardText], async text => {
    return content.eval(`
      document.addEventListener("copy", function(e) {
        e.preventDefault();
        e.clipboardData.setData("text/plain", "${text}");
      }, { once: true });
    `);
  });
  // trigger keyboard shortcut to copy.
  await EventUtils.synthesizeAndWaitKey(
    "c",
    kIsMac ? { accelKey: true } : { ctrlKey: true }
  );
  return clipboardText;
}, "keyboard shortcut with custom data");

testPasteContextMenuSuppression(async aBrowser => {
  const clipboardText = "X" + Math.random();
  await SpecialPowers.spawn(aBrowser, [clipboardText], async text => {
    let div = content.document.createElement("div");
    div.innerText = text;
    content.document.documentElement.appendChild(div);
    // select text
    content
      .getSelection()
      .setBaseAndExtent(div.firstChild, text.length, div.firstChild, 0);
    return SpecialPowers.doCommand(content, "cmd_copy");
  });
  return clipboardText;
}, "copy command");

async function readTypes(aBrowser) {
  return SpecialPowers.spawn(aBrowser, [], async () => {
    content.document.notifyUserGestureActivation();
    let items = await content.eval(`navigator.clipboard.read();`);
    return items[0].types;
  });
}

add_task(async function test_context_menu_suppression_image() {
  await BrowserTestUtils.withNewTab(kContentFileUrl, async function (browser) {
    await SpecialPowers.spawn(browser, [], async () => {
      let image = content.document.createElement("img");
      let copyImagePromise = new Promise(resolve => {
        image.addEventListener(
          "load",
          e => {
            let documentViewer = content.docShell.docViewer.QueryInterface(
              SpecialPowers.Ci.nsIDocumentViewerEdit
            );
            documentViewer.setCommandNode(image);
            documentViewer.copyImage(documentViewer.COPY_IMAGE_ALL);
            resolve();
          },
          { once: true }
        );
      });
      image.src =
        "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD4AAABHCAIAAADQjmMaAA" +
        "AACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3goUAwAgSAORBwAAABl0RVh0Q29tbW" +
        "VudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAABPSURBVGje7c4BDQAACAOga//OmuMbJG" +
        "AurTbq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6u" +
        "rq6s31B0IqAY2/tQVCAAAAAElFTkSuQmCC";
      content.document.documentElement.appendChild(image);
      await copyImagePromise;
    });

    info("Test read from cross-origin frame");
    let pasteButtonIsShown = waitForPasteContextMenu();
    let readTypesRequest1 = readTypes(browser.browsingContext.children[1]);
    await pasteButtonIsShown;

    info("Test read from same-origin frame before paste contextmenu is closed");
    // If the cached data is used, it uses type order in cached transferable.
    SimpleTest.isDeeply(
      await readTypes(browser.browsingContext.children[0]),
      ["text/html", "text/plain", "image/png"],
      "read from same-origin should just be resolved without showing paste contextmenu shown"
    );

    info("Dismiss paste button, cross-origin request should be rejected");
    await promiseDismissPasteButton();
    // XXX edgar: not sure why first promiseDismissPasteButton doesn't work on Windows opt build.
    await promiseDismissPasteButton();
    await Assert.rejects(
      readTypesRequest1,
      /NotAllowedError/,
      "cross-origin request should be rejected"
    );
  });
});

function testPasteContextMenuSuppressionPasteEvent(
  aTriggerPasteFun,
  aSuppress,
  aMsg
) {
  add_task(async function test_context_menu_suppression_paste_event() {
    await BrowserTestUtils.withNewTab(
      kContentFileUrl,
      async function (browser) {
        info(`Write data by in cross-origin frame`);
        const clipboardText = "X" + Math.random();
        await SpecialPowers.spawn(
          browser.browsingContext.children[1],
          [clipboardText],
          async text => {
            content.document.notifyUserGestureActivation();
            return content.eval(`navigator.clipboard.writeText("${text}");`);
          }
        );

        info("Test read should show contextmenu");
        let pasteButtonIsShown = waitForPasteContextMenu();
        let readTextRequest = readText(browser);
        await pasteButtonIsShown;

        info("Click paste button, request should be resolved");
        await promiseClickPasteButton();
        is(await readTextRequest, clipboardText, "Request should be resolved");

        info("Test read in paste event handler");
        readTextRequest = SpecialPowers.spawn(browser, [], async () => {
          content.document.notifyUserGestureActivation();
          return content.eval(`
          (() => {
            return new Promise(resolve => {
              document.addEventListener("paste", function(e) {
                e.preventDefault();
                resolve(navigator.clipboard.readText());
              }, { once: true });
            });
          })();
        `);
        });

        if (aSuppress) {
          let listener = function (e) {
            if (e.target.getAttribute("id") == kPasteMenuPopupId) {
              ok(!aSuppress, "paste contextmenu should not be shown");
            }
          };
          document.addEventListener("popupshown", listener);
          info(`Trigger paste event by ${aMsg}`);
          // trigger paste event
          await aTriggerPasteFun(browser);
          is(
            await readTextRequest,
            clipboardText,
            "Request should be resolved"
          );
          document.removeEventListener("popupshown", listener);
        } else {
          let pasteButtonIsShown = waitForPasteContextMenu();
          info(
            `Trigger paste event by ${aMsg}, read should still show contextmenu`
          );
          // trigger paste event
          await aTriggerPasteFun(browser);
          await pasteButtonIsShown;

          info("Click paste button, request should be resolved");
          await promiseClickPasteButton();
          is(
            await readTextRequest,
            clipboardText,
            "Request should be resolved"
          );
        }

        info("Test read should still show contextmenu");
        pasteButtonIsShown = waitForPasteContextMenu();
        readTextRequest = readText(browser);
        await pasteButtonIsShown;

        info("Click paste button, request should be resolved");
        await promiseClickPasteButton();
        is(await readTextRequest, clipboardText, "Request should be resolved");
      }
    );
  });
}

// If platform supports selection clipboard, the middle click paste the content
// from selection clipboard instead, in such case, we don't suppress the
// contextmenu when access global clipboard via async clipboard API.
if (
  !Services.clipboard.isClipboardTypeSupported(
    Services.clipboard.kSelectionClipboard
  )
) {
  testPasteContextMenuSuppressionPasteEvent(
    async browser => {
      await SpecialPowers.pushPrefEnv({
        set: [["middlemouse.paste", true]],
      });

      await SpecialPowers.spawn(browser, [], async () => {
        EventUtils.synthesizeMouse(
          content.document.documentElement,
          1,
          1,
          { button: 1 },
          content.window
        );
      });
    },
    true,
    "middle click"
  );
}

testPasteContextMenuSuppressionPasteEvent(
  async browser => {
    await EventUtils.synthesizeAndWaitKey(
      "v",
      kIsMac ? { accelKey: true } : { ctrlKey: true }
    );
  },
  true,
  "keyboard shortcut"
);

testPasteContextMenuSuppressionPasteEvent(
  async browser => {
    await SpecialPowers.spawn(browser, [], async () => {
      return SpecialPowers.doCommand(content.window, "cmd_paste");
    });
  },
  true,
  "paste command"
);

testPasteContextMenuSuppressionPasteEvent(
  async browser => {
    await SpecialPowers.spawn(browser, [], async () => {
      let div = content.document.createElement("div");
      div.setAttribute("contenteditable", "true");
      content.document.documentElement.appendChild(div);
      div.focus();
      return SpecialPowers.doCommand(content.window, "cmd_pasteNoFormatting");
    });
  },
  false,
  "pasteNoFormatting command"
);