简体   繁体   English

如何循环处理请求的javascript页面?

[英]How to loop a javascript page that handles requests?

I'm trying to loop this page for my chrome extension using javascript.我正在尝试使用 javascript 为我的 chrome 扩展程序循环此页面。 What it does is it should keep running until it gets a response from "chrome.tabs.sendMessage" to stop running.它的作用是它应该继续运行,直到它收到来自“chrome.tabs.sendMessage”的响应以停止运行。 The response function from "chrome.tabs.sendMessage" sends the correct boolean, but the rest of the code below does not work. “chrome.tabs.sendMessage”的响应函数发送正确的布尔值,但下面的其余代码不起作用。 When I run this code, console.log(cont) prints first, but console.log(response[0]) should be running first.当我运行此代码时,console.log(cont) 首先打印,但 console.log(response[0]) 应该首先运行。 I think it's an issue with async programming, but I am new to javascript and this kind of programming so I'm not sure how to fix it.我认为这是异步编程的一个问题,但我是 javascript 和这种编程的新手,所以我不确定如何解决它。 Any advice or help is appreciated, thanks!任何建议或帮助表示赞赏,谢谢!

var temp = false;

function injectTheScript() {
    var name = document.getElementById('name').value;

     chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
         chrome.tabs.executeScript(tabs[0].id, {file: "utilities.js"}, function(){
             chrome.tabs.sendMessage(tabs[0].id, name, function(response){
                temp = response[0];
                console.log(response[0]);
            });
        });
    });
    return temp;
}

function nextName() {
    var cont = true;
    while(cont){
        cont = injectTheScript();
        console.log(cont); //this gets printed first but should be printed second
    }
}

document.getElementById('start').addEventListener('click', nextName);

This page is popup.js btw, it is the script behind popup.html, what the chrome extension shows when you click the icon.这个页面是 popup.js 顺便说一句,它是 popup.html 背后的脚本,当你点击图标时,chrome 扩展显示的内容。

Each JavaScript script's context is single-threaded so your synchronous while loop will keep running forever in one event loop task, meaning none of the asynchronous callbacks of query(), executeScript(), and sendMessage() will ever run, and your extension will consume 100% CPU endlessly.每个 JavaScript 脚本的上下文都是单线程的,因此您的同步while循环将在一个事件循环任务中永远运行,这意味着 query()、executeScript() 和 sendMessage() 的异步回调都不会运行,您的扩展将无休止地消耗 100% CPU。

The solution is to make the loop asynchronous and let injectTheScript return the content script's response value via Promise :解决方案是使循环异步并让 injectTheScript 通过Promise返回内容脚本的响应值:

function injectTheScript() {
  return new Promise(resolve => { 
    const name = document.getElementById('name').value;
    chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => {
      chrome.tabs.executeScript(tab.id, {file: 'utilities.js'}, () => {
        chrome.tabs.sendMessage(tab.id, name, resolve);
      });
    });
  });
}

async function nextName() {
  while (await injectTheScript()) {
    console.log('yay');
  }
}

The above code expects your onMessage listener in content script to return a boolean value via sendResponse:上面的代码期望内容脚本中的 onMessage 侦听器通过 sendResponse 返回一个布尔值:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // do something
  // ..............
  sendResponse(true); // or false
});

See tutorials on Promise and asynchronous JavaScript for more info if needed.如果需要,请参阅有关Promise和异步 JavaScript 的教程以获取更多信息。

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

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