Non blocking alert for a chrome extension popup window

家住魔仙堡 提交于 2021-02-07 17:11:04

问题


I'm making a chrome extension and for it I need to add in some non blocking alerts to the pop up window. Regular alerts pause the javascript code execution and the client does not want that. I tried using jQuery's UI Dialog box but when I click the "OK" button to close it, the popup window loses focus and closes as well. Any advice on how to either add persistence to the popup window or on how to create a non blocking alert from the popup?

UPDATE: The problem is that content.js is the one creating the alert. So when i click it the popup loses focus and closes. Is there any way that I can create an alert attached to popup.html instead of to the page loaded in the current tab?


回答1:


Simply display the dialog in the popup window because it can only display content inside its rigidly limited bounds (maximum 750px or 800px) and you can't "attach" something from outside.

  1. Send a message from your content script and wait for the reponse in a listener:

    if (someCondition) {
        chrome.runtime.sendMessage({action: "alert", text: "STOP!"});
    }
    
    chrome.runtime.onMessage.addListener(function(msg) {
        if (msg.action == "alert-response") {
            doSomething(msg.response);
        }
    });
    
  2. All open popups receive the message, the active one shows an alert UI and when any of its buttons are clicked a response message is sent to the content script with an id of the button:

    chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
        if (msg.action == "alert") {
            // if several popups are visible in different windows only one should respond
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                if (tabs[0].id == sender.tab.id) {
                    showAlert(msg.text);
                }
            });
        }
    });
    
    function showAlert(text) {
        // show the nonblocking dialog
        ................................
        btnOK.addEventListener("click", buttonClick);
        btnCancel.addEventListener("click", buttonClick);
        function buttonClick(event) {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {
                    action: "alert-response",
                    response: event.target.id // id of the clicked button: "ok", "cancel"
                }
            });
        }
    }
    


来源:https://stackoverflow.com/questions/33007804/non-blocking-alert-for-a-chrome-extension-popup-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!