0

I have this strange problem:

on content_script:

function getText(){
    var = text;
    chrome.extension.sendMessage({}, function(response){
        text = response.data;
    });
    return text;
}

if (getText()) {
    console.log('OK')
} else{ 
    console.log('Not OK')
}

on background.js:

var text = 'tests';

chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
    sendResponse( { 'data': text } );
})

Place a breakpoint on line return text and you get OK on console.

Disable breakpoints and you get only Not OK.;

Seems to be some timing problem, like text not being defined at the time of return, unless you give Chrome some time by using a breakpoint.

manifest.json:

{
  ...
  "permissions": ["tabs"],
  "background": {
    "scripts": ["js/background.js"]
  },
  "content_scripts": [ 
        {
            ...
            "js": [ "js/content_script.js"], 
            "run_at": "document_end"
    } 
  ],
  "manifest_version": 2
}

Can someone reproduce this?

motobói
  • 1,687
  • 18
  • 24
  • 1
    Read http://stackoverflow.com/a/11689804/938089 – Rob W Aug 31 '12 at 22:09
  • possible duplicate of [After calling chrome.tabs.query, the results are not available](http://stackoverflow.com/questions/11688171/after-calling-chrome-tabs-query-the-results-are-not-available) – Rob W Aug 31 '12 at 22:09
  • What is your question? If your question is how to implement `getText` function. The answer is "do not return value in `getText` using `return` syntax. Give a parameter `callback` to `getText`, when `getText` receives result from `sendMessage`, it will return text via `callback`." – Jacob Dam Sep 02 '12 at 04:54

0 Answers0