summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/permissions-policy/experimental-features/resources/focus-without-user-activation-iframe-tentative.html
blob: 3d5aab95addddace39fb67d16eaf2e1ef2824475 (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
<!doctype html>
<input autofocus onfocus="autofocus_onfocus()"/>
<script>
  let autofocused = false;
  function autofocus_onfocus() {
    autofocused = true;
  }

  /**
   * @param target object: Target to call |focus()| with.
   * @param timeout integer | undefined: Timeout to wait for the focus event.
   * If unspecified, a timeout will not be set.
   * @param focus_target boolean | undefined: Wether to focus the target after
   * listening for |onfocus| event.
   */
  function wait_focus_event(target, timeout, focus_target) {
    return new Promise((resolve) => {
      if (timeout)
        setTimeout(() => resolve(false), timeout);

      target.onfocus = () => resolve(true);
      if (focus_target)
        target.focus();
    });
  }

  function post_result(destination, result) {
    destination.postMessage({focused: result}, "*");
  }

  window.addEventListener("message", (e) => {
    if (e.data.event === "autofocus") {
      if (autofocused)
        post_result(e.source, true);

      wait_focus_event(document.querySelector("input"), e.data.timeout)
        .then(result => post_result(e.source, result));
    } else if (e.data.event === "focus-window") {
      wait_focus_event(window, e.data.timeout, true /* focus_target */)
        .then(result => post_result(e.source, result));
    } else if (e.data.event === "focus-input") {
      const input_element = document.querySelector("input");
      wait_focus_event(input_element, e.data.timeout, true /* focus_target */)
        .then(result => post_result(e.source, result));
    }
});
</script>