希望在导航菜单项上执行悬停操作,该菜单项应该显示子菜单。
chrome.scripting.executeScript(
{
target: {tabId: tabId},
func: hoverFunction,
args:[id]
},
(injectionResults) => {
// perform something post execution
});
function hoverFunction(id){
let element = document.getElementById(id);
element.addEventListener('mouseover', function() {
console.log('Event triggered');
});
var event = new MouseEvent('mouseover', {
'view': window,
'bubbles': true,
'cancelable': true
});
element.dispatchEvent(event);
}
试图在菜单项上模拟鼠标对事件的影响,当我看到控制台日志被打印时,我看到事件被触发,但是在脚本执行时子菜单不会弹出。
试图模拟/分派鼠标对菜单项上的事件,我看到事件被触发,因为我看到控制台日志被打印,但子菜单不会弹出脚本执行。
我的期望是,我应该能够用脚本自动/执行悬停在元素上,并将预期的事件(本例)、弹出的子菜单或鼠标上方显示的元素的工具提示(如果有的话)显示为happen..In。
发布于 2022-11-28 22:19:45
我试着盲目射击:
在我看来,它很有可能通过添加world:"MAIN" in executeScript来工作。
发布于 2022-12-03 05:29:09
看起来,您试图在元素上分派mouseover事件,但是这个事件不会自动触发任何附加到元素的事件处理程序。相反,您需要手动调用事件处理程序。
尝试:
element.onmouseover();
发布于 2022-12-03 22:41:31
看起来,您正在尝试使用脚本来模拟页面中某个元素上的mouseover事件。但是,重要的是要记住,仅仅在元素上分派mouseover事件并不一定意味着预期的行为(在本例中,子菜单出现)将发生。这是因为元素的事件侦听器和相关行为是由页面上的代码决定的,而不是由脚本决定的。
解决此问题的一种方法是使用executeScript函数将您自己的事件侦听器和行为注入页面。例如,可以使用executeScript将mouseover事件侦听器附加到元素,而在该事件侦听器中,您可以再次使用executeScript运行通常在元素悬停时运行的代码。
下面是您如何做到这一点的一个示例:
// First, use executeScript to attach a mouseover event listener to the element
chrome.scripting.executeScript(
{
target: {tabId: tabId},
func: addMouseoverListener,
args:[id]
},
(injectionResults) => {
// Perform something after the listener is attached
}
);
function addMouseoverListener(id) {
let element = document.getElementById(id);
element.addEventListener('mouseover', function() {
// When the mouseover event is triggered, use executeScript again to run the code that would normally run when the element is hovered over
chrome.scripting.executeScript(
{
target: {tabId: tabId},
code: `
// Code to run when the element is hovered over goes here
console.log('Element hovered over');
`
},
(injectionResults) => {
// Perform something after the code is executed
}
);
});
}
然后可以使用dispatchEvent函数触发元素上的mouseover事件,这将导致事件侦听器运行指定的代码。这将允许您模拟悬停行为并获得预期的结果。
请记住,在元素悬停时需要运行的确切代码将取决于页面的特定实现,因此您可能需要调整代码以满足您的需要。此外,您可能需要处理其他事件,如鼠标退出,以便正确地模拟悬停行为。
https://stackoverflow.com/questions/74562896
复制相似问题