Firefox Extension trouble using port.emit and port.on - javascript

I can't seem to get port.emit working correctly with my Firefox extension. From the init() function in popup.js the messages are correctly sent to main.js using addon.port.emit. Once they've been sent, the giveStorage message is correctly received in popup.js. However, this only works correctly when the original message is sent in the init function.
When I try sending the messages using using the jQuery change listener, the logs "Storage has been set." and "Sending storage to popup.js" come through, so popup.js is just not receiving it, but I have no idea why not. Only messages are logged correctly when ran from the init function.
If anyone has any ideas, or if you need any more information, please let me know and I'll see what I can do. Any help is greatly appreciated!
main.js
panel.port.on("setStorage", function (text) {
console.log("Storage has been set.");
ss.storage[text[0]] = text[1];
})
panel.port.on("getStorage", function (text) {
console.log("Sending storage to popup.js");
panel.port.emit("giveStorage", [text, ss.storage[text]])
})
popup.js
function init(){
$(".panel").hide();
addon.port.emit("getStorage", "username");
addon.port.emit("getStorage", "volume");
setInterval(function(){following();}, 60000);
}
addon.port.on("giveStorage", function (text) {
console.log("Message received from main.js");
if (text[1] !== null) {
if (text[0] === "username") {
username = text[1];
$('#menuFollowing').click();
}
else if (text[0] === "volume"){
volume = text[1];
$("#volume").val(volume);
$('#volumeValue').empty();
$('#volumeValue').append('Volume: ' + volume);
}
}
})
$('#volume').change(function(){
volume = $('#volume').val();
addon.port.emit("setStorage", ["volume", volume]);
addon.port.emit("getStorage", "volume");
});
Complete main.js
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var self = require("sdk/self");
var ss = require("sdk/simple-storage");
var notifications = require("sdk/notifications");
var panel = panels.Panel({
width: 500,
height: 500,
contentURL: self.data.url("popup.html"),
onHide: handleHide,
});
var button = ToggleButton({
id: "hitbox-plus",
label: "hitbox Plus",
icon: {
"16": "./icon16.png",
"48": "./icon48.png",
},
onChange: handleChange,
});
function handleChange(state) {
panel.contentURL = self.data.url("popup.html");
if (state.checked) {
panel.show({
position: button
});
}
}
function handleHide() {
button.state('window', {checked: false});
}
panel.port.on("getStorage", function (text) {
console.log("Sending storage to popup.js");
panel.port.emit("giveStorage", [text, ss.storage[text]])
})
panel.port.on("setStorage", function (text) {
console.log("Storage has been set.");
ss.storage[text[0]] = text[1];
})

Related

In extension the callbacks are accumulating and persisting until browser restart

I am porting a chess game parser to new manifest v3 specification. When clicking context menu on a selected text, it plays visually the selected text as PGN chess game notation.
The problem is that background script on each game execution adds one more chrome.runtime.onMessage listener, and all the listeners persists until browser closed. So, all listeners are invoked and only first game is played each time.
There is the code:
//background.js
function playBoard (info, imgPath, windowAttributes)
{
console.log("play board with: " + info.selectionText);
let gameObject = {
chessObject:
{
gametype : "PGN_OR_FEN_board",
content : info.selectionText,
imgPath : imgPath
}
};
let windowPromise = chrome.windows.create(windowAttributes);
windowPromise.then((value) => {
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) =>
{
console.log("backg: chrome.runtime.onMessage()> " + gameObject.chessObject.content);
sendResponse(gameObject);
}
);
});
}
The above code is invoked in following context:
//background.js
console.log("enter global>");
var idParser = "parser parent";
var idMiniBoard = "board mini";
var idMediuBoard = "board medium";
chrome.runtime.onInstalled.addListener(
(details)=>
{
console.log("on installing");
idParser = chrome.contextMenus.create({"id":idParser, "title": "Chess Parser", "contexts":["selection"]});
idMiniBoard = chrome.contextMenus.create({"id":idMiniBoard, "title": "Play Small", "contexts":["selection"], "parentId": idRoatta});
idMediuBoard = chrome.contextMenus.create({"id":idMediuBoard, "title": "Play Medium", "contexts":["selection"], "parentId": idRoatta});
chrome.contextMenus.onClicked.addListener(menuItemClick);
console.log("on installed");
}
)
function menuItemClick(clickData, tab)
{
switch (clickData.menuItemId)
{
case idMiniBoard:
playBoard (clickData, "mini18", {url: "board.html", type:"popup", height : 350, width : 350});
return;
case idMediuBoard:
playBoard (clickData, "medium35", {url: "board.html", type:"popup", height: 450, width: 450});
return;
}
}
There is the popup window startup code
document.addEventListener('DOMContentLoaded',
(event) =>
{
chrome.runtime.sendMessage({ chessObject: { gametype : "PGN_OR_FEN_board" } },
(request) => //in fact is response, but is requested response
{
board_doc_main(request.chessObject);
});
}
);
I am trying to apply similar approach as I did for firefox, here Firefox extension, identification of context. Somehow for firefox this works. I am trying to implement like this: Popup open on click from background worker. Then popup window sends message to background worker to receive the required context, including the selection game text.
###################
UPDATE:
As suggested in response from #wOxxOm, this is exactly how I changed now
function playBoard (clickData, imgPath, windowAttributes)
{
let gameObject = {
chessObject:
{
gametype : "PGN_OR_FEN_board",
content : clickData.selectionText,
imgPath : imgPath
}
};
let windowPromise = chrome.windows.create(windowAttributes);
windowPromise.then((wnd) => {
chrome.runtime.onMessage.addListener (
function __playBoardCallback__ (request, sender, sendResponse)
{
if (sender.tab?.id === wnd.tabs[0].id)
{
chrome.runtime.onMessage.removeListener(__playBoardCallback__);
sendResponse(gameObject);
}
}
);
});
}
Unregister the listener immediately when it runs by using a named function:
async function playBoard(info, imgPath, windowAttributes) {
let gameObject = {
// .........
};
const wnd = await chrome.windows.create(windowAttributes);
const tabId = wnd.tabs[0].id;
chrome.runtime.onMessage.addListener(function _(msg, sender, sendResponse) {
if (sender.tab?.id === tabId) {
chrome.runtime.onMessage.removeListener(_);
sendResponse(gameObject);
}
});
}

Check if notification exists in JavaScript

Chrome browser.
The script is executed every time the page is refreshed.
Is it possible to verify the existence of a notification so as not to duplicate it.
if ($('.snippet__title').length) {
var titles = document.querySelectorAll('.snippet__title')
titles.forEach((title) => {
if (title.textContent.includes('searchString')) {
var msg = title.textContent.trim()
var notification = new Notification('Element found', {
body: msg,
dir: 'auto',
icon: 'icon.jpg'
});
}
})
}
Thanks mplungjan. So I thought to do it, but I thought there are still some solutions.
Working solution using localStorage
var NotifyShowed = localStorage.getItem('NotifyShowed')
if (!NotifyShowed) {
if ($('.snippet__title').length) {
var titles = document.querySelectorAll('.snippet__title')
titles.forEach((title) => {
if (title.textContent.includes('searchString')) {
var msg = title.textContent.trim()
var notification = new Notification('Element found', {
body: msg,
dir: 'auto',
icon: 'icon.jpg'
});
localStorage.setItem('NotifyShowed', true);
}
})
}
}

My IndexedDB add() in my service worker succeed but I cannot see the data it in the Chrome dev tools Application/Storage

I am on Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra,
I managed to get a service worker working, but I must say I am new at this.
I now try to get it to use an IndexedDB and store data in it.
It fetches data from a local web server in http and retrieve it without problem in json format.
The data format is :
[{"id":"1", "...":"...", ...},
{"id":"2", "...":"...", ...},
{"id":"3", "...":"...", ...},
...
{"id":"n", "...":"...", ...}]
it then adds the data to an IndexedDB without problem apparently because the onsuccess callback is triggered ...
entityObjectStore.add success : Event {isTrusted: true, type: "success", target: IDBRequest, currentTarget: IDBRequest, eventPhase: 2…}
But it does not appear in the Chrome dev tools!
Here is my service worker:
self.addEventListener('install',function(event)
{
event.waitUntil(
(new Promise(function(resolve,reject)resolve()}))
.then(function()
{return self.skipWaiting();}));
});
self.addEventListener('activate', function(event)
{
event.waitUntil(
(new Promise(function(resolve,reject){resolve()}))
.then(function() {return self.clients.claim();}));
});
self.addEventListener('message', function(event)
{
if(event.data.command=="data.load")
{
var options = event.data.options
var url = new URL(event.data.host+options.source);
var parameters = {entity:options.name,
options:encodeURIComponent(options.options)};
Object.keys(parameters)
.forEach(key => url.searchParams.append(key,
parameters[key]))
fetch(url).then(function(response)
{
if(response.ok)
{
response.json().then(function(data_json)
{
var entityData = data_json;
var request = indexedDB.open(options.name);
request.onerror = function(event)
{
console.log("indexedDB.open error :",event);
};
request.onsuccess = function(event)
{
console.log("indexedDB.open success :",event)
var db = event.target.result;
}
request.onupgradeneeded = function(event)
{
console.log("indexedDB.open upgrade :",event)
var db = event.target.result;
db.createObjectStore(options.options.id, { keyPath: "id" });
objectStore.transaction.oncomplete = function(event)
{
var entityObjectStore = db.transaction(options.options.id, "readwrite").objectStore(options.options.id);
for (var i in entityData)
{
var addRequest = entityObjectStore.add(entityData[i]);
addRequest.onerror = function(event)
{
console.log("entityObjectStore.add error :",event);
};
addRequest.onsuccess = function(event)
{
console.log("entityObjectStore.add success :",event);
};
}
}
};
});
}
});
}
else if(event.data.command=="data.get")
{
var command = event.data;
var request = indexedDB.open(command.domain);
request.onerror = function(event)
{
console.log("indexedDB.open error :",event);
};
request.onsuccess = function(event)
{
console.log("indexedDB.open success :", event)
var db = event.target.result;
var transaction = db.transaction([command.domain]);
var objectStore = transaction.objectStore(command.entity);
var request = objectStore.get(command.id);
request.onerror = function(event)
{
console.log("objectStore.get error :",event);
};
request.onsuccess = function(event)
{
console.log("objectStore.get success :",event);
console.log("request.result=" + request.result);
};
}
}
});
Here is the HTML file I use with it :
<!DOCTYPE html>
<html>
<head>
<title>My service worker app</title>
</head>
<body>
<button id="update">Update</button>
<div id="log"></div>
<script type="text/javascript">
function sendMessage(message)
{
return new Promise(function(resolve, reject)
{
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event)
{
if (event.data.error)
{
reject(event.data.error);
}
else
{
resolve(event.data);
}
};
});
}
if (navigator.serviceWorker.controller)
{
var url = navigator.serviceWorker.controller.scriptURL;
var initData = [
{
name:"my_entity_type",
source:"/webapp/data",
options:{id:"my_entity_type_id"}
}
]
for(var dataIndex in initData)
{
var data = initData[dataIndex]
sendMessage({
command:"data.load",
host: document.location.origin,
options: data
});
}
}
else
{
navigator.serviceWorker.register('/webapp/lt_sw.js')
.then(function(registration)
{
debug('Refresh to allow ServiceWorker to control this client', 'onload');
debug(registration.scope, 'register');
});
}
navigator.serviceWorker.addEventListener('controllerchange',
function()
{
var scriptURL = navigator.serviceWorker.controller.scriptURL;
debug(scriptURL, 'oncontrollerchange');
});
document.querySelector('#update').addEventListener('click',
function()
{
navigator.serviceWorker.ready.then(function(registration)
{
registration.update()
.then(function()
{
console.log('Checked for update');
})
.catch(function(error)
{
console.error('Update failed', error);
});
});
});
function debug(message, element)
{
var target = document.querySelector('#log');
console.log(element,":",message)
target.textContent = message;
}
</script>
</body>
</html>
Any idea about what I am, doing wrong?
Edit 1:
I modified the script in the html file so that update mechanism sends another message to the service worker asking for data :
document.querySelector('#update').addEventListener('click',
function()
{
navigator.serviceWorker.ready.then(function(registration)
{
registration.update()
.then(function()
{
console.log('Checked for update');
sendMessage({
command:"data.get",
domain:"database_name",
entity: "my_entity_type",
id: "my_entity_id"
});
})
.catch(function(error)
{
console.error('Update failed', error);
});
});
});
And I added the following line:
indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){ console.log("data.get all dbs:",sender.target.result); };
Just at the beginning of the data look up part:
else if(event.data.command=="data.get")
{
To list all the IndexedDBs on Chrome as explained here : https://stackoverflow.com/a/15234833/2360577
And I get all the databases I created previously!
data.get all dbs: DOMStringList {0: "db1", 1: "db2", 2: "db3", 3: "db4", length: 4}
Then I proceeded to list all ObjectStores in these dbs, also as explained in the previous link, by adding the following line :
indexedDB.open(<databaseName>).onsuccess = function(sender,args)
{"<databaseName>'s object stores",console.log(sender.target.result.objectStoreNames); };
And apart for one, where the data is processed and apparently does not work, they all had one object store with the same name as the db that contains it as expected ...
db1's object stores DOMStringList {0: "db1", length: 1}
db2's object stores DOMStringList {length: 0}
db3's object stores DOMStringList {0: "db3", length: 1}
db4's object stores DOMStringList {0: "db4", length: 1}
Then I had a look inside the object stores ...
indexedDB.open("db3").onsuccess = function(event)
{event.target.result.transaction(["db3"]).objectStore("db3")
.getAll().onsuccess = function(event)
{console.log("objectStore.getAll() success :",event.target.result)};};
And the entries are there as expected! But not in Application/Storage ...
Edit 2:
The error for db2 was apparently that I did not refresh the data in the database ... this part works now ...
Edit 3:
The answer was as simple as closing and reopening the dev tools ... like #wOxxOm suggested ...
It works for me if I close DevTools and open again. Did you try that?
You could also check the "Update on reload" button and try hard reset ctrl/shift+f5 to the same effect as #wOxxOm mentioned.

Google Chrome extension to close notification after user click

The Chrome extension works fine. My problem is that the notification closes in 7 seconds. I want for the user click to close the notification.
function engine(){
var latestId;
var ids;
var messages = [];
var newmessage = [];
$.get('http://localhost/site/json.php',function (data){
var json = $.parseJSON(data);
messages = json;
ids = json[0].id;
if(latestId == ids){
//no update
}else if(latestId === undefined){
var run = {
type: "basic",
title: "Title",
message: "Some message",
iconUrl : "icon.png",
};
chrome.notifications.create(run);
}
});
}
First create your notification and give it a notificationID parameter to close it later.
var notification = {
type:"basic",
title:"News From Us!",
message:"Google Chrome Updated to v50!",
iconUrl:"assets/images/icon.png"
};
chrome.notifications.create("notfyId",notification);
On notification click you can close notification using its id (which is "notfyId")
function forwardNotfy(){
chrome.notifications.clear("notfyId");
window.open(url); //optional
}
chrome.notifications.onClicked.addListener(forwardNotfy);
Now, when you click your notification it'll close.
This feature is currently only implemented in the beta channel, and not in the latest version of chrome. See here for details.
When it is implemented, you will be able to use requireInteraction : True like:
var run = {
type: "basic",
title: "Title",
message: "Some message",
iconUrl : "icon.png",
requireInteraction : True,
}
to implement this.
You can use notification.close();:
setTimeout(function() {
notification.close();
}, 2000);
Demo:
// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: "Hey there! You've been notified!x",
});
notification.onclick = function () {
window.open("http://stackoverflow.com/a/13328397/1269037");
};
setTimeout(function() {
notification.close();
}, 2000);
}
}
<button onclick="notifyMe()">
Notify me!
</button>
JSBin Demo
notification.close() is used to close any notification.
For more information please see the below code-
To create the notification:
var notification = new Notification('OnlineOfferPrice', {
icon: 'icon.png',
body: "Test Message",
});
If you want to perform operation on notification click please use the below code. After your business logic it will automatically close-
notification.onclick = function () {
//write your business logic here.
notification.close();
};
If notification is not clicked and you want to close it automatically after 6 seconds-
setTimeout(function() { notification.close(); }, 6000);

How can I remove a whole IndexedDB database from JavaScript?

How can one remove a whole IndexedDB database from JavaScript, as opposed to just an object store? I'm using the IndexedDB shim, which may use WebSQL as its backend.
I'd mainly like to know how to do this for the PhantomJS (headless) browser, although Chrome, Safari (on iPad) and IE10 are other important browsers.
As far as I can tell, one should use indexedDB.deleteDatabase:
var req = indexedDB.deleteDatabase(databaseName);
req.onsuccess = function () {
console.log("Deleted database successfully");
};
req.onerror = function () {
console.log("Couldn't delete database");
};
req.onblocked = function () {
console.log("Couldn't delete database due to the operation being blocked");
};
I can confirm that it works with PhantomJS 1.9.0 and Chrome 26.0.1410.43.
I found that the following code works OK but to see the DB removed in the Chrome Resources Tab I have had to refresh the page.
Also I found I had problems with the Chrome debug tools running while doing transactions. Makes it harder to debug but if you close it while running code the code seems to work OK.
Significant also is to set a reference to the object store when opening the page.
Obviously the delete part of the code is in the deleteTheDB method.
Code derived from example provided by Craig Shoemaker on Pluralsight.
var IndDb = {
name: 'SiteVisitInsp',
version: 1000,
instance: {},
storenames: {
inspRecords: 'inspRecords',
images: 'images'
},
defaultErrorHandler: function (e) {
WriteOutText("Error found : " + e);
},
setDefaultErrorHandler: function (request) {
if ('onerror' in request) {
request.onerror = db.defaultErrorHandler;
}
if ('onblocked' in request) {
request.onblocked = db.defaultErrorHandler;
}
}
};
var dt = new Date();
var oneInspRecord =
{
recordId: 0,
dateCreated: dt,
dateOfInsp: dt,
weatherId: 0,
timeArrived: '',
timeDeparted: '',
projectId: 0,
contractorName: '',
DIWConsultant: '',
SiteForeman: '',
NoOfStaffOnSite: 0,
FileME: '',
ObservationNotes: '',
DiscussionNotes: '',
MachineryEquipment: '',
Materials: ''
};
var oneImage =
{
recordId: '',
imgSequence: 0,
imageStr: '',
dateCreated: dt
}
var SVInsp = {
nameOfDBStore: function () { alert("Indexed DB Store name : " + IndDb.name); },
createDB: function () {
openRequest = window.indexedDB.open(IndDb.name, IndDb.version);
openRequest.onupgradeneeded = function (e) {
var newVersion = e.target.result;
if (!newVersion.objectStoreNames.contains(IndDb.storenames.inspRecords)) {
newVersion.createObjectStore(IndDb.storenames.inspRecords,
{
autoIncrement: true
});
}
if (!newVersion.objectStoreNames.contains(IndDb.storenames.images)) {
newVersion.createObjectStore(IndDb.storenames.images,
{
autoIncrement: true
});
}
};
openRequest.onerror = openRequest.onblocked = 'Error'; //resultText;
openRequest.onsuccess = function (e) {
//WriteOutText("Database open");
IndDb.instance = e.target.result;
};
},
deleteTheDB: function () {
if (typeof IndDb.instance !== 'undefined') {
//WriteOutText("Closing the DB");
IndDb.instance.close();
var deleteRequest = indexedDB.deleteDatabase(IndDb.name)
deleteRequest.onblocked = function () {
console.log("Delete blocked.");
}
deleteRequest.onerror =
function () {
console.log("Error deleting the DB");
//alert("Error deleting the DB");
};
//"Error deleting the DB";
deleteRequest.onsuccess = function () {
console.log("Deleted OK.");
alert("*** NOTE : Requires page refresh to see the DB removed from the Resources IndexedDB tab in Chrome.");
//WriteOutText("Database deleted.");
};
};
}
}

Categories

Resources