popup.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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('main');
  20. }
  21. });
  22. });
  23. }
  24. document.addEventListener('DOMContentLoaded', function() {
  25. if (!localStorage.settingsUrl) {
  26. show('setup');
  27. tryToDetectSettings();
  28. } else {
  29. show('main');
  30. }
  31. document.getElementById('actionAdd').addEventListener('click', add);
  32. getCurrentTabUrl(function(url) {
  33. document.getElementById('content').value = url;
  34. });
  35. });
  36. var views = [
  37. 'main',
  38. 'done',
  39. 'setup',
  40. 'busy'
  41. ];
  42. function show(view) {
  43. views.forEach(function (view) {
  44. document.getElementById(view).classList.add('hide');
  45. });
  46. document.getElementById(view).classList.remove('hide');
  47. }
  48. function add() {
  49. show('busy');
  50. var http = new XMLHttpRequest();
  51. var body = JSON.stringify({ content: document.getElementById('content').value });
  52. http.open('POST', localStorage.settingsUrl, true);
  53. http.setRequestHeader('Content-type', 'application/json');
  54. http.setRequestHeader('Content-length', body.length);
  55. http.setRequestHeader('Connection', 'close');
  56. http.onreadystatechange = function() {//Call a function when the state changes.
  57. if(http.readyState === 4) {
  58. if (http.status === 401) {
  59. delete localStorage.settingsUrl;
  60. show('setup');
  61. return;
  62. }
  63. if (http.status === 201) return show('done');
  64. }
  65. };
  66. http.send(body);
  67. }