When I send a message from background script to popup .js I get an error receiving end does not exist. I also tried chrome.tabs.sendmessage and chrome.tabs.onupdate but nothing works.
Background.js
set_badge();
setInterval(function () {
set_badge();
}, 300000);
function set_badge() {
settings = "";
chrome.storage.sync.get("settings", function (result) {
settings = result.settings;
var url = "https://domaintube.net/json-example1.php?sessiondis=1234," + settings;
fetch(url)
.then(response => response.json())
.then(data => {
chrome.browserAction.setBadgeText({text: data["message"].length.toString()});
var myAudio = new Audio(chrome.runtime.getURL("clearly.mp3"));
myAudio.play();
chrome.runtime.sendMessage({todo: "fetch"}, function () {
alert("working");
});
});
});
}
popup js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.todo == "fetch") {
alert("Working");
get_message();
}
});
function get_message() {
settings = "";
chrome.storage.sync.get("settings", function (result) {
settings = result.settings;
var url = "https://domaintube.net/json-example1.php?sessiondis=1234," + settings;
fetch(url)
.then(response => response.json())
.then(message => {
chrome.browserAction.setBadgeText({text: message["message"].length.toString()});
for (var i = 0; i < message["message"].length; i++) {
$(".message").append("<h4>" + message["message"][i]["title"] + "</h4>");
$(".message").append("<p>" + message["message"][i]["description"] + "</p>");
$(".message")
.append("<a href=" + message["message"][i]["url"] + " target='_blank'>" +
message["message"][i]["url"] + "</a>");
}
});
});
}
Related
I am trying to pass the Input value from content script to background script and persist this value until changed in the extension.
However, the value is saved on the content script but it is not available in the background script.
Here is the Extension HTML:
<input type="text" class="InputControl form-control" id="Key"/>
<button class="save-to-key" id="saveButton" type="button">Save</button>
Here is content script that triggers based on the button click:
//use strict';
var KeyInput = document.getElementById("Key");
var SaveButton = document.getElementById("saveButton");
function SaveButtonclick() {
if(KeyInput.value!==""){
chrome.storage.local.set({'key': KeyInput.value}, function() {
chrome.runtime.sendMessage({messageType:"KeyData",Key:KeyInput.value});
console.log(" click event value " + KeyInput.value);
alert("Value currently is set by script " + KeyInput.value);
//window.close();
if(chrome.runtime.lastError) {
console.error(
"Error setting'key to " + JSON.stringify(KeyInput.value) +
": " + chrome.runtime.lastError.message
);
}
});
chrome.storage.local.get("Key").then((result) => {
console.log("extracted from storage" + result.Key);// this is undefined for some reason
});
}
}
//document.addEventListener('DOMContentLoaded', SaveButtonclick , false);
SaveButton.addEventListener('click',SaveButtonclick,false);
chrome.runtime.onSuspend.addListener(() => {
console.log("Unloading.");
});
Here is the background script:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if(message.messageType=="KeyData"){
chrome.storage.local.set({"Key":message.key});
console.log("Value currently is from message listeners "+message.key);
sendResponse({'message':"KeyDataSavedSuccessfully"})
}
});
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
id: "1",
title: "Save!",
contexts:["selection"] // ContextType
});
});
var KeyValue = function(word){
var query = word.selectionText;
var Key;
chrome.storage.local.get("Key").then((result) => {
Key=result.Key;
});
console.log("Value currently is Main Script and get defaultvalues function is" + Key);
chrome.tabs.create({url: "https://example.com/v1/test?sid="+query+"&Key="+Key+"&test=true"});
};
chrome.contextMenus.onClicked.addListener(KeyValue);
Hope you can help.
I noticed where i was going wrong! I am not waiting for the result so the value is undefined.
I changed the extension script here:
//use strict';
var KeyInput = document.getElementById("Key");
var SaveButton = document.getElementById("saveButton");
function SaveButtonclick() {
if(KeyInput.value!==""){
chrome.storage.local.set({'key': KeyInput.value}, function() {
chrome.runtime.sendMessage({messageType:"KeyData",Key:KeyInput.value},function (response) {
console.log("message sent to backgroud "+JSON.stringify(response));
});
console.log(" click event value " + KeyInput.value);
alert("Value currently is set by script " + KeyInput.value);
//window.close();
if(chrome.runtime.lastError) {
console.error(
"Error setting key to " + JSON.stringify(KeyInput.value) +
": " + chrome.runtime.lastError.message
);
}
});
chrome.storage.local.get("Key").then((result) => {
console.log("extracted from storage" + result.Key);// this is undefined for some reason
});
}
}
//document.addEventListener('DOMContentLoaded', SaveButtonclick , false);
SaveButton.addEventListener('click',SaveButtonclick,false);
chrome.runtime.onSuspend.addListener(() => {
console.log("Unloading.");
});
I changed this part in the background Script:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if(message.messageType=="KeyData"){
var Keyvaluetosave=message.Key;
chrome.storage.local.set({"Key":Keyvaluetosave});
console.log("Value currently is from message listeners "+Keyvaluetosave);
sendResponse({'message':"KeyDataSavedSuccessfully"})
}
});
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
id: "1",
title: "Save!",
contexts:["selection"] // ContextType
});
});
var KeyValue = function(word){
var query = word.selectionText;
var Key;
chrome.storage.local.get("Key").then((result) => {
Key=result.Key;
console.log("Value currently is Main Script and get defaultvalues function is" + Key);
chrome.tabs.create({url: "https://example.com/v1/test?sid="+query+"&Key="+Key+"&test=true"});
});
};
I did type in some part here on the... but this does fix the issue .. value is passed. If any one can improve this then please do so . Thank you so much...!
We are trying to download a 7 GB from CDN using JSZip.js. The chrome browser suddenly seems to close the connection when the download reaches 3.5gb every time. The approximate time is around 15 mins. Is there a way we increase the tolerant time to 1 hr say?
$("#downloadJSZip").on('click', function () {
var result = [{ "cdn": "url....", "filename": "7.84 gb.zip", "size": 4194304, "path": "7.84 gb" }];
var Promise = window.Promise;
if (!Promise) {
Promise = JSZip.external.Promise;
}
function urlToPromise(url) {
return new Promise(function(resolve, reject) {
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
reject(err);
} else {
resolve(data);
}
});
});
}
var fileNameArray = [];
function changeFileName(fileName,j){
var i = fileName.lastIndexOf('.');
var newfilename = fileName.slice(0,i)+"--"+j+fileName.slice(i);
if(fileNameArray.indexOf(newfilename) != -1){
j = j+1;
changeFileName(fileName,j);
}
return newfilename;
}
var zip = new JSZip();
// find every checked item
result.forEach(function(file){
var filename = file.filename;
if(fileNameArray.indexOf(filename) != -1){
var newfilename = changeFileName(filename,1);
filename = newfilename;
}
fileNameArray.push(filename);
var url = file.cdn;
var folder = (file.path);
zip.folder(folder).file(filename, urlToPromise(url), {binary:true});
// zip.file(filename, urlToPromise(url), {binary:true});
});
// when everything has been downloaded, we can trigger the dl
zip.generateAsync({type:"blob",
}, function updateCallback(metadata) {
var msg = "progression : " + metadata.percent.toFixed(2) + " %";
if(metadata.currentFile) {
msg += ", current file = " + metadata.currentFile;
}
console.log(msg);
console.log(metadata.percent|0);
})
.then(function callback(blob) {
// see FileSaver.js
//console.log("blob=====>");
//console.dir(blob);
//saveAs(blob, "example.zip") ;
saveAs(blob, $scope.folderName+".zip") ;
//console.log("done !");
}, function (e) {
});
});
Is this chrome browser configuration?
I have some files downloaded and I wanna push them to a server. Every time I try to push the file I get the error
Error: Can't set headers after they are sent.
I have a for loop that reads all the files and parse them and after that I want to send them to the server one by one.
app.get('/dataparser', function(req, res) {
var fs = require('fs');
var obj;
var jsonGis = new Array();
var jsonArray;
var filePaths = [];
const downloadFolder = './sampletest/';
var mtimes = {};
var reloadTimes = 10000;
fs.readdir(downloadFolder, (err, files) => {
files.forEach(file => {
filePaths.push("sampletest/" + file);
});
})
var execFunction = function() {
for (var i = 0; i < filePaths.length; i++) {
parseFile(filePaths[i], mtimes[filePaths[i]]);
}
};
execFunction();
setInterval(execFunction, reloadTimes);
function parseFile(fileName, lastModifiedTime) {
fs.stat(fileName, function(err, fd) {
for (var i=0, len = filePaths.length; i<len; i++) {
if (fd.mtime !== lastModifiedTime) {
mtimes[fileName] = fd.mtime;
fs.readFile(filePaths[i], function(err, data) {
if (err) {
return console.error(err);
}
obj = JSON.parse(data);
jsonGis.push('"Person1"');
jsonGis.push('"' + obj.pages[1].answers[2].values[0] + '"');
jsonGis.push('"person2"');
jsonGis.push('"' + obj.pages[1].answers[0].values[0] + '"');
jsonGis.push('"codewals"');
jsonGis.push('"42343GSDS"');
jsonGis.push('"geometry":{');
jsonGis.push('"x":' + obj.pages[1].answers[4].values[0].coordinates.latitude + ',');
jsonGis.push('"y":' + obj.pages[1].answers[4].values[0].coordinates.longitude);
var str = "[{ " + jsonGis[0] + jsonGis[1] + jsonGis[2] + ": " + jsonGis[3] + "," + jsonGis[4] + ": " + jsonGis[16] + "}}]"
//pushing to the server
console.log("check here");
console.log(str);
var qs = require("querystring");
var http = require("http");
var options = {
"method": "POST",
"hostname": "twst2.gtw.com",
"port": null,
"path": "localpath/",
"headers": {
"accept": "application/json",
"content-type": "application/x-www-form-urlencoded",
}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(qs.stringify({features: str}));
res.send("The server was updated");
req.end();
});
}
}
});
};
Just need to send the data to the server from file1.json and then file2.json then file3.json and so on.
Try creating a separate callback function that includes .write, .send, and .end, then let it be the callback for .request.
I want create function for reset form with use kendo element and other HTML element. I create this function:
function resetForm() {
var formName = $(this).data("form");
var form = $(formName);
if (form) {
//orginal reset
form.trigger("reset");
//custom reset
$(formName + " input").each(function () {
var cb = $(this).data("kendoDropDownList");
if (cb) {
cb.value("");
cb.text("");
}
});
}
}
Not work correctly!
I found this way:
if (form) {
//custom reset
$(formName + " input[data-role='dropdownlist']").each(function () {
var item = $(this).data("kendoDropDownList");
if (item && $(this).attr('id') != 'AgeType' && $(this).attr('id') != 'AllAnyType') {
item.value("");
item.text("");
}
});
$(formName + " input.k-textbox").each(function () {
$(this).val("");
});
$(formName + " input[data-role='numerictextbox']").not("#TopNumber").each(function () {
var item = $(this).data("kendoNumericTextBox");
if (item) {
item.value("");
}
});
$(formName + " textarea").each(function () {
$(this).val("");
});
$(formName + " :checkbox").each(function () {
this.checked = !this.checked;
});
$(formName + " input[type=text]").each(function () {
$(this).val("");
});
}
i am trying to create an application where products are received on every second and updating a database of fixed size (~ 300 MB) using the LRU policy. Although i have no exception on adding new products and deleting them from the database, it seems that Chrome never deletes the .ldb and .bak files. As such, I spend several gigabytes of hard disk and i always reach the quota limit. The same code works perfect on Firefox. Can someone explain me what am i doing wrong? Below you can find the code.
startExperiment(300 * 1024 * 1024);
function startExperiment(lrusize:number) {
var j = 0;
var productsToInsert = new HashMap<number, Product>();
window.indexedDB.deleteDatabase("ExampleDatabase");
var versionNumber = 1;
var stats = new Stats();
var sizeOfDatabase = 0;
var db = new ProductDatabase('ExampleDatabase', versionNumber, () => {
db.getSizeOfDatabase((result) => {
if(result == null) {
sizeOfDatabase = 0;
} else {
sizeOfDatabase = result;
}
});
});
function randomizeArray() {
var numOfMBS = Math.floor((Math.random() * (10 - 2) + 2) * 1024 * 1024);
var bytearray = new Uint8Array(numOfMBS.valueOf());
for (var i = 0; i < bytearray.length; i++) {
bytearray[i] = Math.random() * (100 - 1) + 1;
}
return bytearray;
}
setInterval(function () {
var readAverage = stats.getReadTimesAverage();
var writeAverage = stats.getWriteTimesAverage();
var deleteAverage = stats.getDeleteTimesAverage();
console.log("Num of insertions : " + j + " | Read average : " + readAverage + " | Write average : " + writeAverage + " | Delete average : " + deleteAverage);
}, 5000);
setInterval(function () {
var bytearray = randomizeArray();
var identifier = j++;
var timestamp = Date.now();
db.getProduct(identifier, (product) => {
if (product == null) {
var newProduct = new Product(identifier, timestamp, 0, bytearray);
var size = memorySizeOf(newProduct);
newProduct.sizeInBytes = size;
productsToInsert.set(identifier, newProduct);
}
});
}, 1000);
function updateLRU() {
var tmpList:Product[] = [];
var keys = productsToInsert.keys();
var currentBytesToBeInserted = 0;
for (var i = 0; i < keys.length; i++) {
var product = productsToInsert.get(keys[i]);
tmpList.push(product);
currentBytesToBeInserted += product.sizeInBytes;
}
var currentSize = sizeOfDatabase + currentBytesToBeInserted;
if (currentSize > lrusize) {
var bytesToRemove = currentSize - lrusize;
db.deleteProducts(bytesToRemove, stats, () => {
sizeOfDatabase -= bytesToRemove;
addFragments(tmpList);
});
} else {
addProducts(tmpList);
}
}
function addProducts(tmpList:Product[]) {
var product = tmpList[0];
var startAddProductTs = Date.now();
db.addProduct(product, () => {
var stopAddProductTs = Date.now();
stats.addWriteTimes(stopAddProductTs - startAddProductTs);
sizeOfDatabase += product.sizeInBytes;
tmpList.shift();
productsToInsert.delete(product.productId);
if(tmpList.length > 0) {
addProducts(tmpList);
} else {
db.addDBSize(sizeOfDatabase, () => {
});
}
});
}
setInterval(function () {
updateLRU();
}, 20000);
}
class ProductDatabase {
private db;
constructor(private name:string, private version:number, callback:() => void) {
this.openDatabase(callback);
}
openDatabase(callback:() => void) {
var openDatabaseRequest = window.indexedDB.open(this.name, this.version);
openDatabaseRequest.onupgradeneeded = this.upgrade;
openDatabaseRequest.onsuccess = () => {
this.db = openDatabaseRequest.result;
callback();
}
}
upgrade(event:any) {
var store = event.target.result.createObjectStore("products", {keyPath: 'productId'});
store.createIndex('by_timestamp', "timestamp", {unique: true});
event.target.result.createObjectStore("dbsize", {keyPath: 'sizeId'});
}
getProduct(productId:number, callback:(result:Product) => void) {
var productStore = this.db.transaction(["products"], "readonly").objectStore('products');
var query = productStore.get(productId);
query.onsuccess = () => {
var product = query.result;
callback(product);
}
query.onerror = () => {
console.error("Read product error : " + query.error);
}
}
addDBSize(dbSize:number, callback:() => void) {
var transaction = this.db.transaction('dbsize', 'readwrite');
var productStore = transaction.objectStore('dbsize');
var newSize = {'sizeId': 1, 'bytelength': dbSize};
var request = productStore.put(newSize);
request.onerror = () => {
console.log("Unsuccessful request with error : " + request.error);
}
transaction.oncomplete = () => {
callback();
}
transaction.onerror = () => {
console.error("fucking error : " + transaction.error);
}
transaction.onabort = () => {
console.error("Shit. transaction is aborted with error : " + transaction.error);
}
}
addCachedProducts(productList:Array<Product>, callback:() => void) {
var transaction = this.db.transaction('products', 'readwrite');
var productStore = transaction.objectStore('products');
for (var i = 0; i < productList.length; i++) {
productStore.add(productList[i]);
}
transaction.oncomplete = () => {
callback();
}
transaction.onabort = () => {
console.error("Shit. transaction is aborted with error : " + transaction.error);
}
}
getNumberOfProducts(callback:(result:number) => void) {
var productStore = this.db.transaction('products', 'readonly').objectStore('products');
var query = productStore.count();
query.onsuccess = () => {
var result = query.result;
callback(result);
}
query.onerror = () => {
console.error("Read number of products error : " + query.error);
}
}
getSizeOfDatabase(callback:(result:number) => void) {
var productStore = this.db.transaction('dbsize', "readonly").objectStore('dbsize');
var query = productStore.get(1);
query.onsuccess = () => {
var product = query.result;
callback(product);
}
query.onerror = () => {
console.error("Read databasesize error : " + query.error);
}
}
deleteProducts(numOfBytes:number, stats:Stats, callback:() => void) {
var transaction = this.db.transaction('products', 'readwrite');
var productStore = transaction.objectStore('products');
var index = productStore.index('by_timestamp');
var request = index.openCursor();
request.onsuccess = function () {
var cursor = request.result;
if (cursor) {
var cursorBytes = cursor.value.sizeInBytes;
var startDeleteTs = Date.now();
var deleteRequest = cursor.delete();
deleteRequest.onsuccess = () => {
var stopDeleteTs = Date.now();
stats.addDeleteTimes(stopDeleteTs - startDeleteTs);
numOfBytes -= cursorBytes;
if (numOfBytes > 0) {
cursor.continue();
}
}
deleteRequest.onerror = () => {
console.error("Delete product error : " + deleteRequest.error);
}
}
}
transaction.oncomplete = () => {
callback();
}
transaction.onabort = () => {
console.log("Delete transaction aborted with error : " + transaction.error);
}
}
addProduct(product:Product, callback:() => void) {
var transaction = this.db.transaction('products', 'readwrite');
var productStore = transaction.objectStore('products');
var request = productStore.put(product);
request.onerror = () => {
console.log("Unsuccessful request with error : " + request.error);
}
transaction.oncomplete = () => {
callback();
}
transaction.onerror = () => {
console.error("fucking error : " + transaction.error);
}
transaction.onabort = () => {
console.error("Shit. transaction is aborted with error : " + transaction.error);
}
}
}
In Chrome, there is a delay between deleting data through the IndexedDB API and having it deleted from disk. Usually that's fine. But in my experience, sometimes it never gets deleted from disk, which is really bad when the user has exceeded their quota because then you can never store any more data even if you delete everything.
Thanks dumbmatter. Unfortunately my experience also showed me that Chrome never deletes the unnecessary files. The problem is that IndexedDB in Chrome use LevelDB as an implementation and it rarely calls compact. However, i found a solution using PouchDB which leverages both IndexedDB and LevelDB api and i can explicitly call compact and delete my unnecessary files.