2016-05-14 77 views
2

我已經完成了開發Chrome擴展程序的主要功能,但我一直在努力保留popup.html文件中的用戶首選項。所以,我在popup.html文件中有一個按鈕,該按鈕應該是用戶首選項,但在重新加載頁面並再次單擊擴展時,我無法保留用戶首選項。在popup.html Chrome擴展程序中保存用戶偏好

我嘗試過使用Chrome存儲API,但無法實現我想要的功能。 這裏是popup.html的圖片:

enter image description here

我希望能夠保存用戶的偏好,如果他們選擇打開和關閉之間切換。但就我現在的情況而言,當用戶滑過它(如圖所示)時,一旦從彈出框中單擊並再次單擊該圖標,該按鈕將始終默認爲「關閉」位置。

我嘗試使用localStorage和Chrome存儲API的組合來加載用戶首選項,但我無法這樣做。

這裏是我的popup.js文件:

function saveChanges() { 
    // Get a value. 
    if ($('#myonoffswitch').is(':checked')) { 
     localStorage.mydata = 'y'; 
    } else { 
     localStorage.mydata = 'n'; 
    } 
    // Save it using the Chrome extension storage API. 
    chrome.storage.sync.set({ 
     'value': localStorage.mydata 
    }, function() { 

    }); 
} 

$(document).ready(function() { 
    if (localStorage.getItem('mydata')) { 
     if (localStorage.mydata == 'n') { 
      $('myonoffswitch').attr('checked', false); 
     } else { 
      $('myonoffswitch').attr('checked', true); 
     } 
    } else { 
     if ($('#myonoffswitch').is(':checked')) { 
      localStorage.setItem('mydata', 'y'); 
     } else { 
      localStorage.setItem('mydata', 'n'); 
     } 
    } 

    $('#myonoffswitch').click(function() { 
     saveChanges(); 
    }); 

}); 

這裏是我的popup.html文件:

<html> 

<head> 
    <title>Replace some text</title> 
    <link rel="stylesheet" type="text/css" href="popup.css"> 
    <script type='text/javascript' src='jquery-1.12.3.js'></script> 
    <script type="text/javascript" src="options.js"></script> 
</head> 

<body> 

    <div> 
     <div class='logo'> 

     </div> 
     <div class='main-text'> 

     </div> 
     <div class='buttons-area'> 
      <div class="onoffswitch"> 
       <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch"> 
       <label class="onoffswitch-label" for="myonoffswitch"></label> 
      </div> 
      <div class='block-spoilers-message'> 
       On Off Button 
      </div> 
     </div> 
    </div> 

</body> 

</html> 

最後,這裏是我的內容腳本的相關部分:

$(document).ready(function() { 

    var on_off_pref = true; 

    chrome.storage.onChanged.addListener(function (changes, namespace) { 
     for (key in changes) { 
      var storageChange = changes[key]; 
      on_off_pref = storageChange.newValue; 
      console.log('Storage key "%s" in namespace "%s" changed. ' + 
       'Old value was "%s", new value is "%s".', 
       key, 
       namespace, 
       storageChange.oldValue, 
       storageChange.newValue); 
     } 
    }); 

    if (on_off_pref === 'y') { 
     //Execute main functionality here only if the button in popup.html is on. 
    } 
}); 

因此,簡而言之,我需要保留popup.html上的設置並在內容腳本中使用這些設置來確定磨損她或不運行主要部分。 我已經看過其他的StackOverflow解決方案,但我還沒有能夠得到他們的任何工作。 任何幫助解決這個問題將深受讚賞!

+1

投票結束爲排印錯誤。你只是在'$('myonoffswitch')中忘記了'#'。attr('checked',true);' – Xan

回答

相關問題