popup.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. // Query filter to be passed to chrome.tabs.query - see
  3. // https://developer.chrome.com/extensions/tabs#method-query
  4. var queryInfo = {
  5. active: true,
  6. currentWindow: true
  7. };
  8. // localStorage.settingsUrl = 'https://things.nebulon.info/api/things?token=70c40f76-75cb-49a0-bf97-e06815208baf';
  9. function getCurrentTabUrl(callback) {
  10. chrome.tabs.query(queryInfo, function(tabs) {
  11. callback(tabs[0].url);
  12. });
  13. }
  14. function tryToDetectSettings() {
  15. chrome.tabs.query(queryInfo, function(tabs) {
  16. chrome.tabs.executeScript(tabs[0].id, { file: 'detectapp.js' }, function (results) {
  17. if (results[0] && results[0].addPostUrl) {
  18. localStorage.settingsUrl = results[0].addPostUrl;
  19. show('home');
  20. }
  21. });
  22. });
  23. }
  24. tryToDetectSettings();
  25. document.addEventListener('DOMContentLoaded', function() {
  26. if (!localStorage.settingsUrl) {
  27. show('setup');
  28. } else {
  29. show('main');
  30. }
  31. document.getElementById('actionAdd').addEventListener('click', add);
  32. document.getElementById('disconnectButton').addEventListener('click', disconnectApp);
  33. getCurrentTabUrl(function(url) {
  34. document.getElementById('content').value = url;
  35. });
  36. });
  37. var views = [
  38. 'main',
  39. 'done',
  40. 'home',
  41. 'disconnected',
  42. 'setup',
  43. 'busy'
  44. ];
  45. function show(view) {
  46. views.forEach(function (view) {
  47. document.getElementById(view).classList.add('hide');
  48. });
  49. document.getElementById(view).classList.remove('hide');
  50. }
  51. function disconnectApp() {
  52. delete localStorage.settingsUrl;
  53. show('disconnected');
  54. }
  55. function add() {
  56. show('busy');
  57. var http = new XMLHttpRequest();
  58. var body = JSON.stringify({ content: document.getElementById('content').value });
  59. http.open('POST', localStorage.settingsUrl, true);
  60. http.setRequestHeader('Content-type', 'application/json');
  61. http.setRequestHeader('Content-length', body.length);
  62. http.setRequestHeader('Connection', 'close');
  63. http.onreadystatechange = function() {//Call a function when the state changes.
  64. if(http.readyState === 4) {
  65. if (http.status === 401) {
  66. delete localStorage.settingsUrl;
  67. show('setup');
  68. return;
  69. }
  70. if (http.status === 201) return show('done');
  71. }
  72. };
  73. http.send(body);
  74. }