How to make dynamic changes to popup.html in Chrome extensions

此生再无相见时 提交于 2020-05-17 06:50:05

问题


I'd like to understand how can I make changes to the HTML of popup.html in a Chrome extension that reloads a given URL every x seconds and looks for a certain text in the webpage.

More precisely: the extension's UI has two buttons "Run" and "Stop", respectively running and stopping the reload-and-search function above. I also wanted to include in the UI a "loading" gif to display when the user clicks on the "Run" button and the extension is searching for the text. The loading gif should disappear either when the user clicks on the "Stop" button (and the extension stops searching) or when the the text is found on the target website.

The loading gif is inside an invisible with id="searching" in popup.html:

<div id="searching" style="display: none;" align="center"><img  src="loading.gif" style="width: auto; height: 30%"/></div>

and I tried to reach the desired outcome by adding in app.js two functions that change its attributes, as well as chrome.runtime.onMessage.addListener (in addition to backround.js):

 function showSrc() {
   document.getElementById('searching').style.display ='block';
 } 

 function hideSrc() {
   document.getElementById('searching').style.display ='none';
 }

 document.querySelector('.button-run').addEventListener('click', () => {chrome.runtime.sendMessage('start'); showSrc();});

 document.querySelector('.button-stop').addEventListener('click', () => {chrome.runtime.sendMessage('stop'); hideSrc();});

 chrome.runtime.onMessage.addListener(function(message, callback){
   if(message === 'stop') {
     hideSrc();
   } else if(message === 'run') {
     showSrc();
   }
 });

As you can see from app.js, when the user clicks on "Run" or "Stop", the script not only sends the respective messages to background.js for the extension to perform/stop its reload-and-search function, but also changes the attribute of the with id="searching" so that the loading gif is visible/invisible in the UI accordingly by calling showSrc() or hideSrc(), respectively.

However, this works fine only when I stay with the UI open in the tab where I launch the script. If I switch the tab while the extension is running, then the UI (popup.html) closes and when I reopen it by clicking on the extension's icon, loading.gif is gone although the extension is still running.

How can I fix this?

来源:https://stackoverflow.com/questions/61344376/how-to-make-dynamic-changes-to-popup-html-in-chrome-extensions

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