jquery - executeScript not populating global variable - Chrome Extension -
i building chrome extension , have array variable array_out
empty. need array populated values of array comes within executescript
on callback function.
but, reason global array array_out
isn't being populated, console.log
shows, because chrome function running after jquery?
any help?
the code have follows:
$(document).ready(function(){ var array_out = []; chrome.tabs.query({currentwindow: true, active: true}, function(tabs) { chrome.tabs.executescript(tabs[0].id, { code: " \ var array_in = ['one', 'two', 'three']; \ " }, function(result){ array_out = result[0]; console.log('in: ' + array_out.length); }); }); console.log('out: ' + array_out.length); });
you using 2 functions execute asynchronously. provide callback function both chrome.tabs.query
, chrome.tabs.executescript
attempt access variable set in callback method of chrome.tabs.executescript
.
in order ensure accessing array_out
after has been initialized, must place access code (console.log('out: ' + array_out.length);
) in separate function called @ end of callback function chrome.tabs.executescript
(or directly in callback function itself). doing so, still execute code when $(document).ready()
called, after 2 asynchronous functions have invoked callback functions array contents assigned.
for example:
var array_out = []; $(document).ready(function(){ chrome.tabs.query({currentwindow: true, active: true}, function(tabs) { chrome.tabs.executescript(tabs[0].id, { code: " \ var array_in = ['one', 'two', 'three']; \ " }, function(result){ array_out = result[0]; console.log('in: ' + array_out.length); accessarray(); //you can stuff array_out here... }); }); //console.log('out: ' + array_out.length); //-- array_out not yet set here }); function accessarray() { console.log('out: ' + array_out.length); //you can more stuff array_out here... }
Comments
Post a Comment