2015-09-10 53 views
0

您好我正在嘗試自動化一段谷歌擴展的代碼來更改地理位置。我希望它與Activate/Deactivate按鈕一起工作: 當我從「Content.js」中刪除IF語句時,它工作正常,但使用IF語句它不起作用。請幫忙。Chrome.runtime無法使用激活按鈕

Options.html

<button id="activate-it">Activate!</button> 
<button id="deactivate-it">Deactivate!</button> 

Background.Js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) 
    {  
      if (request.method == "getStatus") 
      { 
      sendResponse({status: 'activate-it'}); 
      } 
    }); 

Content.Js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) 
{ 
if (response.status == "activate-it") 
    { 
     var lat = "28.22"; 
     var lon = "70.86"; 

     var script = document.createElement('script'); 
     script.innerHTML = 'navigator.geolocation.getCurrentPosition=function(a,b){a({coords:{latitude:'+lat+',longitude:'+ lon +'},timestamp:Date.now()})};var position={coords:{latitude:'+lat+',longitude:'+lon+'}};'; 
     document.head.insertBefore(script, document.head.firstChild); 
    } 

    else if (response.status!="activate-it") 
    { 
     var scripts = document.getElementsByTagName('script'); 

     for(var i = 0; i < scripts.length; i++) 
     { 
     if(scripts[i].text.indexOf("coords") !== -1) 
     { 
      scripts[i].text = scripts[i].text.replace(/position\.coords\.latitude/g, lat); 
      scripts[i].text = scripts[i].text.replace(/position\.coords\.longitude/g, lon); 
      scripts[i].text = scripts[i].text.replace(/coords\.latitude/g, lat); 
      scripts[i].text = scripts[i].text.replace(/coords\.longitude/g, lon); 
     } 
     } 

    } 
}); 

回答

0

你有一個語法錯誤:sendResponse({status: 'activate-it']});

更改它以這樣的:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) 
{  
     if (request.method == "getStatus") 
     { 
     sendResponse({status: 'activate-it'}); 
     } 
}); 
+0

不起作用。我已經想到了代碼的實際流程,但仍然陷入同樣的​​情況。 「content.js」似乎只適用於從「background.js」發送的「response.status」。我試圖在background.js上打開一個開關,但它不適用於我。我也更新了新的更改。 –