0

I have used message passing in my chrome extension to move data from the background.js to the content.js file.

Within the function below when I output the variable to the console within the function I get the data I expect. When I try the same outside of the function I get null (as defined in the global variable).

Does anyone have an idea how I can pull the data out of the function so I can post it with my AJAX call.

Code

var capturedData = "url=" + window.location.href;
var localHash = "localhash=" + CryptoJS.MD5(capturedData);
var email = null;

chrome.extension.sendMessage({greeting: "hello"}, function(response) {
    email = response;
    console.log(JSON.stringify(email));
    return true;
});
console.log(JSON.stringify(email));


$.ajax({
    type: 'post',
    url: 'url',
    data: {"url":capturedData, "localhash":localHash},
    dataType: 'json',
    success : function (data) {
        if(data.url)
        {
            console.log(data.url);
        }  
    }
});

Output

null content.js:10 {"email":"[email protected]"} content.js:7

Thanks!

1
  • 1
    You can't (or you really don't want to). You should make the AJAX call from inside the first callback. Just throw your AJAX call in a function, then invoke it in the callback. Commented Apr 3, 2015 at 23:10

1 Answer 1

1

You need to make your ajax call after you get some value on email:

var capturedData = "url=" + window.location.href;
var localHash = "localhash=" + CryptoJS.MD5(capturedData);
var email = null;

chrome.extension.sendMessage({greeting: "hello"}, function(response) {
    email = response;
    console.log(JSON.stringify(email));


$.ajax({
    type: 'post',
    url: 'url',
    data: {"url":capturedData, "localhash":localHash},
    dataType: 'json',
    success : function (data) {
       if(data.url)
       {
        console.log(data.url);
       }  
    }
 });

return true;
});

 console.log(JSON.stringify(email));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.