首页 > 解决方案 > 如何修复 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();
}

标签: javascriptgoogle-chrome-extension

解决方案


您的代码在每个 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', '*');
  })
}

推荐阅读