webextensions/src/scripts/background.js

44 lines
1.4 KiB
JavaScript

import ext from "./utils/ext";
import storage from "./utils/storage";
ext.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.action === "perform-save") {
var data = request.data;
var url;
var token;
storage.get(['url', 'token'], function(resp) {
url = resp.url;
token = resp.token;
var params = {
v: 1,
u: encodeURIComponent(data.url),
t: encodeURIComponent(data.title),
d: encodeURIComponent(data.description),
api_token: encodeURIComponent(token),
i: encodeURIComponent(data.image),
c: encodeURIComponent(data.comment),
};
var queryString = Object.keys(params).map((key) => {
return key + '=' + params[key];
}).join('&');
fetch(url + "/api/links", {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: new URLSearchParams(queryString)
})
.then(function(response) {
sendResponse({ action: "saved" });
});
// var destination = url+"?v=1&u="+encodeURIComponent(data.url)+"&t="+encodeURIComponent(data.title)+"&m="+encodeURIComponent(token);
// fetch(destination).then(function(response) {
// sendResponse({ action: "saved" });
// });
});
return true; // https://stackoverflow.com/a/20077854
}
}
);