8

鉴于安全隐患,您无法在 JavaScript 中执行此操作。是否有任何其他类型的 Google 扩展/开发 API 可以让我从 Chrome 执行此操作?

4

1 回答 1

4

是的,有一个 Pointer Lock API 来控制鼠标,检查此代码作为 Pointer Lock API 的参考。

示范

转到http://www.google.co.in/并单击 Google 的徽标,您可以从中自定义此代码以控制鼠标移动和动作。

清单.json

添加内容脚本并为页面设置所有权限。

{
    "name":"Pointer Lock",
    "description":"http://stackoverflow.com/questions/14896728/chrome-extension-to-control-mouse-keyword",
    "version":"1",
    "manifest_version":2,
    "content_scripts": [
        {
          "matches": ["http://www.google.co.in/"],
          "js": ["myscript.js"]
        }
    ],
    "permissions":["<all_urls>"]
}

myscript.js

此代码锁定指针移动。

//Check whether browser supports locking or not
var havePointerLock = 'webkitPointerLockElement' in document;
//Get some random element in http://www.google.co.in/ page
var element = document.getElementById("hplogo");
//Bind an event Listener
element.addEventListener("click", function () {
    if (havePointerLock) {
        // Ask the browser to lock the pointer
        element.requestPointerLock = element.webkitRequestPointerLock;
        element.requestPointerLock();
        //Register lock change callback
        document.addEventListener('webkitpointerlockchange', changeCallback, false);
        //Register callback for all errors
        document.addEventListener('webkitpointerlockerror', errorCallback, false);
    } else {
        alert("Your browser does not support Pointer Lock, Please Upgrade it");
    }
});

function moveCallback(e) {
    //Track all mouse movements
    console.log("Mouse Moved ...");
    console.log(e.webkitMovementX);
    console.log(e.webkitMovementY);
}

function changeCallback() {
    //Check for element whether locked is expected element or not
    if (document.webkitPointerLockElement == element) {
        // Pointer was just locked
        // Enable the mousemove listener
        document.addEventListener("mousemove", moveCallback, false);
    } else {
        // Pointer was just unlocked
        // Disable the mousemove listener
        document.removeEventListener("mousemove", moveCallback, false);
    }
}

function errorCallback(e) {
    //Log Errors
    console.log(e);
}

参考

于 2013-02-17T11:10:07.177 回答