2012-07-21 3 views
1

크롬 확장의 popup.js에 다음 코드가 있습니다.크롬 확장 전역 변수 이상한

var tt; 
chrome.tabs.query({ active: true, currentWindow: true, windowType: 'normal' }, 
    function (tabs) { 
     tt = 5;  
}); 
document.getElementById('elm').textContent = tt; 

그러나 이상한 점은 함수의 측면을 액세스 할 때 TT의 값이 정의되지이지만, document.getElementById('elm').textContent = tt; 함수 내부에 넣어 경우는 "5"를 보여줍니다. 그렇다면 왜 컨트롤이 함수를 빠져 나올 때 변수 값이 유지되지 않습니까?

내가 뭘 잘못하고 있니?

이 코드는 팝업이 표시 될 때 실행됩니다. 나는. 브라우저 동작의 버튼을 클릭하면 코드를 읽을 수있게 단순화했습니다. 사실 현재 탭의 ID를 변수로 가져 오려고합니다. 그러나 아무것도 작동하지 않습니다.

+0

[현재 탭 가져 오기]를 Chrome 확장 프로그램에서 변수에 전달할 수 있습니다. (http://stackoverflow.com/questions/10955408/get-current-tab-and-pass-it-to-variable-in -a-chrome-extension) ('site : stackoverflow.com chrome.tabs.query asynchronous'에 대한 Google 검색의 세 번째 결과 (https://encrypted.google.com/search?q=site:stackoverflow.com) + chrome.tabs.query + asynchronous) 및 [[google-chrome-extension \] + chrome.tabs.query + asynchronous]에 대한 SO 검색의 두 결과 중 하나 (http://stackoverflow.com/search ? q = % 5Bgoogle-chrome-extension % 5D + % 2Bchrome.tabs.query + % 2Basynchronous)). –

답변

1

누군가가이 문제를 다시 만났을 때 대답이 발견되었습니다.

chrome.tabs.query은 비동기 작업이므로 콜백 함수가 나중에 호출되었습니다. 그러나 콜백이 호출되기 전에 document.getElementById('elm').textContent = tt; 행이 실행되어 문제가 발생했습니다. 디버깅 할 때 코드를 단계별로 실행하면 해당 행의 실행이 지연되므로 발생하지 않습니다.