javascript - 如何修复 chrome 扩展上的多确认窗口
问题描述
我正在尝试使用确认选项。但由于某种原因,确认打开多次 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', '*');
})
}
推荐阅读
- php - 如何将环境变量从 .env 加载到 getenv() PHP MVC
- reactjs - 从 React 中的功能组件传递值
- javascript - “禁止(CSRF 令牌丢失或不正确。):”使用 Django 和 JS
- kubernetes - 当 cronjobs 设置为 replace 时,Kubernetes 是否会等待前一个作业完成关闭后再启动新作业?
- javascript - 使用Javascript递归检查对象中的任何空/未定义键/值
- python - 为什么在 RTX 3070/cudnn8/CUDA11.1 上运行时添加卷积/池层会使 Keras/Tensorflow 模型崩溃?
- javascript - 为什么/在哪里多次调用这个 componentDidMount()?
- function - 什么是镜像位的数学(用函数描述)等价物?
- python - docker hub 你是否为每个图像创建一个存储库
- javascript - 如何使用 Pi Vision Web Api 获取过滤后的数据