gpt4 book ai didi

javascript - 如何修复 chrome 扩展上的多重确认窗口

转载 作者:行者123 更新时间:2023-12-02 23:01:57 25 4
gpt4 key购买 nike

我正在尝试使用确认选项。但由于某种原因,确认打开了多次 12-15 次。即使我点击接受一次。

如何修复它只打开一次

popup.js

function injectTheScript() {
// if you don't specify a tab id, executeScript defaults to active tab in current window
chrome.tabs.executeScript({file:'content_script.js', allFrames:true});
// by adding allFrames:true, the code will be run in all the iframes of the webpage, not only the top context
}

document.getElementById('B7').addEventListener('click',injectTheScript);

内容脚本


if(confirm("Are you Sure?")){
var theButton = document.querySelector('.sidebarShowButton'); //a shorter way to select the first element of a class
if (theButton) {
// if the element is present in this context, click on it.
theButton.click();
}
}

var addnote = document.querySelector('.d-icon-note_pencil');
if (addnote) {
// if the element is present in this context, click on it.
addnote.click();
}

最佳答案

您的代码在每个 iframe 中运行,因此您自然会看到多个确认对话框。

如果 theButton 和 addnote 仅存在于一个 iframe 中,那么解决起来很简单:

var buttons = document.querySelectorAll('.sidebarShowButton, .d-icon-note_pencil');
if (buttons.length && confirm('Are you sure?')) {
buttons.forEach(btn => btn.click());
}

否则,您必须通过 window.top.postMessage 使用跨框架消息传递来请求主页的内容脚本允许确认对话框:

const ID = chrome.runtime.id;

if (window === top) {
let confirmed = null;
window.addEventListener('message', event => {
switch (event.data) {
case ID + ':check':
event.source.postMessage(ID + ':' + confirmed, '*');
break;
case ID + ':set-true':
case ID + ':set-false':
confirmed = ID.endsWith('true');
break;
}
});
}

var buttons = document.querySelectorAll('.sidebarShowButton, .d-icon-note_pencil');
if (buttons.length) {
getConfirmStatus().then(confirmed => {
if (confirmed) {
buttons.forEach(btn => btn.click());
}
});
}

function getConfirmStatus() {
return new Promise(resolve => {
window.addEventListener('message', event => {
let status;
switch (event.data) {
case ID + ':true':
case ID + ':false':
status = event.data.endsWith('true');
break;
case ID + ':null':
status = confirm('Are you sure?');
window.top.postMessage(ID + ':set-' + status, '*');
break;
default:
return;
}
resolve(status);
}, {once: true});
window.top.postMessage(ID + ':check', '*');
})
}

关于javascript - 如何修复 chrome 扩展上的多重确认窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com