50963

google chrome extension update text after response callback

Question:

I am writing a Google Chrome extension. I have reached the stage where I can pass messages back and forth readily but I am running into trouble with using the response callback. My background page opens a message page and then the message page requests more information from background. When the message page receives the response I want to replace some of the standard text on the message page with custom text based on the response. Here is the code:

chrome.extension.sendRequest({cmd: "sendKeyWords"}, function(response) { keyWordList=response.keyWordsFound; var keyWords=""; for (var i = 0; i<keyWordList.length; ++i) { keyWords=keyWords+" "+keyWordList[i]; } document.getElementsByClassName("comment")[1].firstChild.innerHTML=keyWords; alert (document.getElementsByClassName("comment")[1].firstChild.innerHTML); });

FIRST QUESTION: This all seems to work fine but the text on the page doesn't change. I am almost certainly because the callback completes after the page is finished loading and the rest of the code finishes before the callback completes, too. How do I update the page with the new text? Can I listen for the callback to complete or something like that?

SECOND QUESTION: The procedure I am pursuing first opens the message page and then the message page requests the keyword list from background. Since I always want the keyword list, it makes more sense to just send it when I create the tab. Can I do that? Here is the code from background that opens the message page:

//when request from detail page to open message page chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if(request.cmd == "openMessage") { console.log("Received Request to Open Message, Profile Score: "+request.keyWordsFound.length); keyWordList=request.keyWordsFound; chrome.tabs.create({url: request.url}, function(tab){ msgTabId=tab.id; //needed to determine if message tab has later been closed chrome.tabs.executeScript(tab.id, {file: "message.js"}); }); console.log("Opening Message"); } });

Along the lines of the second question, I also tried this in background:

//when request from detail page to open message page chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if(request.cmd == "openMessage") { console.log("Received Request to Open Message, Profile Score: "+request.keyWordsFound.length); keyWordList=request.keyWordsFound; var keyWords=""; for (var i = 0; i<keyWordList.length; ++i) { keyWords=keyWords+" "+keyWordList[i]; } console.log(keyWords); chrome.tabs.create({url: request.url}, function(tab){ msgTabId=tab.id; //needed to determine if message tab has later been closed chrome.tabs.executeScript(tab.id, {code: "document.getElementsByClassName('comment')[1].firstChild.innerHTML=keyWords;", file: "message.js"}); }); console.log("Opening Message"); } });

But this doesn't work either, it just breaks and neither script is executed.

Answer1:

I can answer the first part of the question after reading a previous answer by @serg. The problem stems from the asynchronous nature of sendRequest. A callback is required. Here is the code that works:

function getKeyWords(action, callback){ chrome.extension.sendRequest( { cmd: action }, function(response) { callback(response.keyWordsFound); } ); } var keyWords=""; getKeyWords("sendKeyWords", function(reply) { keyWordList=reply; for (var i = 0; i<keyWordList.length; ++i) { keyWords=keyWords+" "+keyWordList[i]; } msgComment1.innerHTML="<strong>"+keyWords+"</strong>"; console.log("reply is:", keyWords); });

Once again, I am indebted to @serg. Thanks.

Recommend

  • calling asp.net codebehind function from javascript
  • Setting Page Title from a SWF
  • How can I replicate a div a certain number of times based on a select-box value?
  • extracting specific information using web::scraper in perl
  • OnChange event handler not working
  • Sending HTML Form Multiple box via POST request with AJAX?
  • Get highlight text in current window and send it in a popup
  • MVC extension method error
  • Angular - routerLinkActive and queryParams handling
  • JSON encode and decode on PHP
  • Element.tagName for python not working
  • Chart.js Multiple dataset
  • How do I get HTML corresponding to current DOM tree?
  • Custom Tabgroup Appcelerator
  • JQuery Internet Explorer and ajaxstop
  • JSON response opens as a file, but I can't access it with JavaScript
  • $wpdb not working in file of WordPress plugin
  • AES padding and writing the ciphertext to a disk file
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • Change an a tag attribute in JavaScript based on screen width
  • Arrays break string types in Julia
  • retrieve vertices with no linked edge in arangodb
  • How to delete a row from a dynamic generate table using jquery?
  • How to set the response of a form post action to a iframe source?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • python draw pie shapes with colour filled
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Running Map reduces the dimensions of the matrices
  • costura.fody for a dll that references another dll
  • Reading document lines to the user (python)
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?