开发者

How to make sure that all keyboard events in the browser is received by one handler

开发者 https://www.devze.com 2023-01-23 08:55 出处:网络
I have encountered a problem regarding keyboard events such as the keydown event. The application is a single page webapp built entirely using JavaScript and DOM manipulation.

I have encountered a problem regarding keyboard events such as the keydown event. The application is a single page webapp built entirely using JavaScript and DOM manipulation.

All keyboard processing is han开发者_开发技巧dled by a single handler added to the document using.

document.addEventListener("keydown", handler, true);

That handler then decodes the keyboard event and delegates an internal keycode to the application framework.

The DOM tree consists only of DIV elements and text nodes.

Now when an iframe with an external HTML document is added, and it contains elements that can receive focus the original handler is bypassed. The only way to restore the key event flow to the original handler is to set focus to the main document.

So it seems like the new document added by the iframe bypasses the capture/bubble event chain from the original document.

This has been tested in chrome for reference, but the actual application runs on an embedded web browser in a set top box, the web browser is based on Webkit.

In the set top box there is no mouse interface so the only input is key events from the remote. This causes a problem for us since we do not want to loose control over the key events when we load other pages using an iframe.

Is the only solution to use an event handler for DOM manipulation and detect when iframes are added and add the main key event handler to the newly inserted document? Or is there a method to ensure that a key event handler always receives all key events within a browser window.

EDIT

I just realized that event handlers can be added to the window object, I will try that as well.

EDIT

Adding the key event handler to the window object did not change anything.


Solved by using the following workaround:

    document.addEventListener("DOMNodeInserted", function (event) {
        if(event.type === "DOMNodeInserted") {
            if(event.srcElement.nodeName === "IFRAME") {
                event.srcElement.addEventListener("keypress", function(kevent) {
                    document.dispatchEvent(kevent);
                    }, true);
             }
         }
    },true);

This propagates key events from child iframes into the main document during the capture phase.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号