How to to initialize keyboard event with given char/keycode in a Chrome extension?

后端 未结 3 1911
生来不讨喜
生来不讨喜 2020-12-03 15:04

I\'m developing a Google Chrome extension which simulates keyboard events on a web-page.

I found that event.initKeyboardEvent() does not work properly b

3条回答
  •  盖世英雄少女心
    2020-12-03 16:01

    Incase anyone has the issue I faced with triggering a keyup with a specific keycode. This is one way.

    First off I tried @RobW's answer above with no luck. No Keycode passed, always undefined.

    So then I looked into @disya2's answer, which did work.

    So here's some code:-

    Manifest

    "permissions": [
        "debugger"
      ],
    

    ContentScript.js

    chrome.runtime.sendMessage({ pressEnter: true });
    

    Background.js

    chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
        if(message.pressEnter){
            chrome.tabs.query({active: true}, function(tabs) {
                chrome.debugger.attach({ tabId: tabs[0].id }, "1.0");
                chrome.debugger.sendCommand({ tabId: tabs[0].id }, 'Input.dispatchKeyEvent', { type: 'keyUp', windowsVirtualKeyCode:13, nativeVirtualKeyCode : 13, macCharCode: 13  });
                chrome.debugger.sendCommand({ tabId: tabs[0].id }, 'Input.dispatchKeyEvent', { type: 'keyDown', windowsVirtualKeyCode:13, nativeVirtualKeyCode : 13, macCharCode: 13  });
                chrome.debugger.detach({ tabId: tabs[0].id });
            });
        }
    });
    

提交回复
热议问题