<!DOCTYPE html> <!-- webkit-test-runner [ useFlexibleViewport=true AsyncClipboardAPIEnabled=true JavaScriptCanAccessClipboard=false ] -->
<html>
    <meta charset="utf8">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <script src="../../resources/js-test.js"></script>
        <style>
            button {
                width: 100px;
                padding: 1em;
            }
        </style>
    </head>
    <script>
        jsTestIsAsync = true;

        description("This test verifies that clipboard items can be written while dispatching the 'copy' event. To manually run the test, copy the 'Copy me' text below.");

        addEventListener("load", async function() {
            const target = document.getElementById("target");

            const textBlob = new Blob([ (new TextEncoder()).encode("Hello world") ], { type : "text/plain" });
            target.addEventListener("copy", async event => {
                try {
                    event.preventDefault();
                    await navigator.clipboard.write([ new ClipboardItem({ "text/plain" : textBlob })]);
                    testPassed("Successfully wrote to clipboard.");
                } catch (exception) {
                    testFailed(`Failed with exception: ${exception}.`);
                } finally {
                    finishJSTest();
                }
            });

            getSelection().selectAllChildren(target);

            if (window.testRunner)
                testRunner.execCommand("Copy");
        });
    </script>
    <body>
        <span id="target">Copy me</span>
    </body>
</html>
