简体   繁体   English

chrome-extension:等待用户输入

[英]chrome-extension: wait for input from user

I am basically wanting to let a user click an element on the page, and have the background.js continue on. 我基本上是想让用户单击页面上的元素,然后继续执行background.js。 The whole action is synchronous, meaning the background script waits for the user input and once it happens it carries on. 整个操作是同步的,这意味着后台脚本会等待用户输入,一旦发生,它将继续进行。 I'm also trying to stop the navigation from happening (ex. when user clicks on a link) but chrome will warn everytime 'Are you sure you want to leave this page?' 我还试图阻止导航的发生(例如,当用户单击链接时),但是chrome每次都会警告您“您确定要离开此页面吗?” I'd like to make it silent. 我想保持沉默。

however, it seems like I can't manipulate the dom from background.js so I put this in the content script instead/ 但是,似乎我无法操纵来自background.js的dom,因此我将其放在内容脚本中/

function getInput(callback) {
    //on click, fire callback, user has finished input
    $(document).on('click', '*', function (e) {
        $(e.target).addClass('highlight');
        callback();
    });

}

Do I now need to implement callback(); 我现在是否需要实现callback(); by sending a message back to the background.js? 通过将消息发送回background.js?

Also, is the dom only manipulatable from the content script and not the background.js? 另外,dom是否只能从内容脚本中操作,而不是background.js?

Chrome extensions are, by design, asynchronous. Chrome扩展程序在设计上是异步的。 You cannot block the browser with extension callbacks in any sane manner. 您不能以任何理智的方式使用扩展回调阻止浏览器。 The only possibility would be to either use the built-in "confirm" method, or to use the webNavigation/webRequest API, which is rather heavy for this task. 唯一的可能性是要么使用内置的“确认”方法,要么使用webNavigation / webRequest API,这对于该任务而言相当繁重。

And no, the background script can not modify the DOM of the page directly. 而且,后台脚本无法直接修改页面的DOM。 You would need to use message passing. 您将需要使用消息传递。

Here is an example using "confirm" 这是使用“确认”的示例

function getInput(callback) {
    //on click, fire callback, user has finished input
    var answer = confirm("Prompt for user here..."); // Provides OK/Cancel button w/ passed message
    if (answer === true) { // The user clicked OK.
        $(document).on('click', '*', function (e) {
            $(e.target).addClass('highlight');
            callback();
        });
    } // The user clicked cancel; else logic here, if needed
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM