Mouse 类
¥Mouse class
Mouse 类在相对于视口左上角的主框架 CSS 像素中运行。
¥The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.
签名:
¥Signature:
export declare abstract class Mouse
备注
¥Remarks
每个 page
对象都有自己的鼠标,可以通过 page.mouse
访问。
¥Every page
object has its own Mouse, accessible with page.mouse
.
此类的构造函数被标记为内部构造函数。第三方代码不应直接调用构造函数或创建扩展 Mouse
类的子类。
¥The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the Mouse
class.
示例 1
¥Example 1
// Using ‘page.mouse’ to trace a 100x100 square.
await page.mouse.move(0, 0);
await page.mouse.down();
await page.mouse.move(0, 100);
await page.mouse.move(100, 100);
await page.mouse.move(100, 0);
await page.mouse.move(0, 0);
await page.mouse.up();
注意:鼠标事件触发合成 MouseEvent
。这意味着它不能完全复制普通用户使用鼠标可以执行的功能。
¥Note: The mouse events trigger synthetic MouseEvent
s. This means that it does not fully replicate the functionality of what a normal user would be able to do with their mouse.
例如,使用 page.mouse
无法拖动和选择文本。相反,你可以使用平台中实现的 DocumentOrShadowRoot.getSelection()
功能。
¥For example, dragging and selecting text is not possible using page.mouse
. Instead, you can use the DocumentOrShadowRoot.getSelection()
functionality implemented in the platform.
示例 2
¥Example 2
例如,如果要选择节点之间的所有内容:
¥For example, if you want to select all content between nodes:
await page.evaluate(
(from, to) => {
const selection = from.getRootNode().getSelection();
const range = document.createRange();
range.setStartBefore(from);
range.setEndAfter(to);
selection.removeAllRanges();
selection.addRange(range);
},
fromJSHandle,
toJSHandle
);
如果你想复制粘贴你的选择,你可以使用剪贴板 api:
¥If you then would want to copy-paste your selection, you can use the clipboard api:
// The clipboard api does not allow you to copy, unless the tab is focused.
await page.bringToFront();
await page.evaluate(() => {
// Copy the selected content to the clipboard
document.execCommand('copy');
// Obtain the content of the clipboard as a string
return navigator.clipboard.readText();
});
注意:如果你想访问剪贴板 API,你必须授予它这样做的权限:
¥Note: If you want access to the clipboard API, you have to give it permission to do so:
await browser
.defaultBrowserContext()
.overridePermissions('<your origin>', ['clipboard-read', 'clipboard-write']);
方法
¥Methods
方法 | 修饰符 | 描述 |
---|---|---|
click(x, y, options) |
| |
down(options) | 按下鼠标。 | |
drag(start, target) | 调度 | |
dragAndDrop(start, target, options) | 按顺序执行拖动、拖动、拖动和放置。 | |
dragEnter(target, data) | 调度 | |
dragOver(target, data) | 调度 | |
drop(target, data) | 按顺序执行 dragenter、dragover 和 drop。 | |
move(x, y, options) | 将鼠标移动到给定的坐标。 | |
reset() | 将鼠标重置为默认状态:没有按下任何按钮;位置在 (0,0)。 | |
up(options) | 释放鼠标。 | |
wheel(options) | 调度 |