Why does chrome.storage.sync.set not load user setting instantly? - javascript

For my chrome extension's options page I have two radio buttons to switch between showing and not showing the buttons on a page. The function works but it takes me a few reloads of the web page before the changes take effect. Does it take some time to save to chrome.storage before the changes take effect/can be used?
here is the JS for my options page:
const saveBtn = document.getElementById('save-btn');
saveBtn.addEventListener('click', () => {
if(document.getElementById('show_btns').checked){
console.log('true');
chrome.storage.sync.set({ btn_disp: true });
} else {
console.log('false');
chrome.storage.sync.set({ btn_disp: false });
}
});
Background script waits for page to load then injects content scripts and css and sends user data with message.
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
//inject the script into page
//only inject on complete load
//listening for the 'complete' message from tabs
if(changeInfo.status === 'complete' && /^http/.test(tab.url)){
chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['./src/js/foreground.js']
})
.then(() => {
console.log('INJECTED');
})
.catch(err => console.log(err));
chrome.scripting.insertCSS({
target: {tabId: tabId},
files: ['./src/css/page_btn_styles.css']
})
.then(() => {
console.log('page_btn_styles.css injected');
sendToForeground();
})
.catch(err => console.log(err));
}
});
//page loaded -> load buttons
function sendToForeground() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { message: 'page_loaded', data: user_data }, (response) => {
console.log('page_loaded message sent');
});
});
}
My content script listens for a message from the background script that the page has loaded. The background script sends the user data object with the message.
//message from background.js that page has loaded
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if(request.message === 'page_loaded'){
const allElements = document.querySelectorAll('*');
for(let i = 0; i < allElements.length; i++) {
if(allElements[i].className.toString().match(/ingredient/g)){
console.log(request.data);
loadPageBtns(request.data);
break;
}
}
}
sendResponse({});
});
JS for loading page buttons in the content script
function loadPageBtns(user_data) {
if(user_data.btn_disp){
//container for buttons on page
let container = document.createElement('div');
container.id = 'btns-container';
//ingredients button
let ingredientsBtn = document.createElement('button');
ingredientsBtn.id = 'ingredients-btn';
ingredientsBtn.classList.add('page-btns');
ingredientsBtn.classList.add('animated');
ingredientsBtn.classList.add('bounceInLeft');
ingredientsBtn.innerText = 'Get Ingredients';
ingredientsBtn.addEventListener('click', () => {
scrollToIngredients();
});
ingredientsBtn.addEventListener('mouseover', () => {
ingredientsBtn.classList.remove('animated');
});
//load event handler for click on recipe
//recipe button
let recipesBtn = document.createElement('button');
recipesBtn.id = 'recipes-btn';
recipesBtn.classList.add('page-btns');
recipesBtn.classList.add('animated');
recipesBtn.classList.add('bounceInLeft');
recipesBtn.innerText = 'Get Recipe';
recipesBtn.addEventListener('click', () => {
scrollToDirections();
});
recipesBtn.addEventListener('mouseover', () => {
recipesBtn.classList.remove('animated');
});
container.appendChild(ingredientsBtn);
container.appendChild(recipesBtn);
document.body.appendChild(container);
}
}

Chrome storage does not seem to save anything when the data is false, i.e. chrome.storage.sync.set({ btn_disp: false });
does not store anything. If it is true then it does store the item.
This can be a problem depending on your default value. If you have a default of TRUE then you end up never being able to store a FALSE value.
I resolved this by storing text true or false rather then boolean.
I can't see your retrieve and default logic so I'm not sure if this is the root of your problem.

Related

Add or remove content script on click of a toggle button inside a chrome popup?

I am developing my first chrome extension, I want to have a toggle button on my popup which allows users to enable or disable the extension for that site, though not completely disable the extension but technically control the execution of the content.js for that particular domain.
Something similar to
popup.js
const toggleBtn = document.querySelector(".toggle");
toggleBtn.addEventListener("click", function(){
if(toggleBtn.checked === true){
console.log('inject content.js');
}else{
console.log('remove content.js');
}
});
I can see there is a way to inject it but there is no way to remove it.
chrome.scripting.executeScript({
target: {tabId},
files: ['content.js'],
});
Note, I don't want to reload the page but want to disable the content.js. How can I achieve this functionality inside my chrome extension. I see there are many extensions doing this like Adblocker and Wordtune.
I went through few SO threads like this one but most of them are for Manifest V2 and few packages that are recommended are obsolate now. I also could not find a complete example anywhere.
Todo
I should be able to turn the extension on/off for the current domain from within the Popup.
It should store the state inside a chrome.storage.sync so that next time I installed the extension I should not again turn on/off for the selected websites.
As soon as I toggle the button, the changes should be visible if I have opened the same domain in another tab.
The extension's icon should be changed in real time as well e.g grey icon for disabled status
If I close and open a website, the icon and the toggle button should be restored their on/off status and update the icon accordingly.
My Attempt (Solves #toDo 1,2,3,4,5)
background.js
const icons = {
enabled: {
'16': 'icon-16.png',
'19': 'icon-19.png',
'38': 'icon-38.png',
'48': 'icon-48.png',
'128': 'icon-128.png'
},
disabled: {
'16': 'icon-16-off.png',
'19': 'icon-19-off.png',
'38': 'icon-38-off.png',
'48': 'icon-48-off.png',
'128': 'icon-128-off.png'
}
};
const getExtensionStatus = host => new Promise((resolve, reject) => {
chrome.storage.sync.get(host, result => {
if (result[host] !== undefined) {
resolve(result[host]);
} else {
setExtensionStatus(host, true);
}
});
});
const setExtensionStatus = (host, toggleBtnStatus) => {
const data = { [host]: toggleBtnStatus };
chrome.storage.sync.set(data, () => {});
};
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === "install") {
chrome.action.setIcon({ path: icons.enabled });
}
});
const init = async tab => {
const url = new URL(tab.url);
if (url.protocol !== "chrome-extension:") {
const host = url.host;
const status = await getExtensionStatus(host);
const icon = status ? icons.enabled : icons.disabled;
chrome.action.setIcon({ path: icon });
}
};
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") init(tab);
});
chrome.tabs.onActivated.addListener(info => {
chrome.tabs.get(info.tabId, init);
});
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
if (request.type === "getExtensionStatus") {
const status = await getExtensionStatus(request.host);
sendResponse({ status });
return true;
} else if (request.type === "setExtensionStatus") {
setExtensionStatus(request.host, request.status);
const icon = request.status ? icons.enabled : icons.disabled;
chrome.action.setIcon({ path: icon });
}
});
popup.js
document.addEventListener("DOMContentLoaded", function () {
const toggleBtn = document.querySelector(".toggle");
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const host = new URL(tabs[0].url).host;
chrome.runtime.sendMessage({ type: "getExtensionStatus", host }, (response) => {
toggleBtn.checked = response.status;
});
toggleBtn.addEventListener("click", () => {
chrome.runtime.sendMessage({ type: "setExtensionStatus", host, status: toggleBtn.checked });
});
});
});
What left?
The content.js is not available after some time of inactiveness of the tab. How can I inject the script again and avoid running event multiple times?
content.js
document.addEventListener("keydown", listenEnterkey);
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "setExtensionStatus") {
console.log(request.status);
if (request.status) {
// Add event listener here
document.addEventListener("keydown", listenEnterkey);
} else {
// Remove event listener here
document.removeEventListener("keydown", listenEnterkey);
}
}
});
For example, if you add a button with a script, I don't think the added button will disappear even if you remove the script.
Therefore, the ON/OFF function is built into the script, and it is operated by the message.
manifest.json
{
"name": "content_scripts + popup",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
{
"js": [
"matches.js"
],
"matches": [
"<all_urls>"
]
}
],
"host_permissions": [
"<all_urls>"
],
"action": {
"default_popup": "popup.html"
}
}
matches.js
console.log("matches.js");
let isEnabled = true;
console.log(isEnabled);
chrome.runtime.onMessage.addListener((message) => {
switch (message) {
case "on":
isEnabled = true;
break;
default:
isEnabled = false;
break;
}
console.log(isEnabled);
});
popup.js
const send = (s) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, s);
});
}
document.getElementById("on").onclick = () => {
send("on");
}
document.getElementById("off").onclick = () => {
send("off");
}
popup.html
<html>
<body>
<button id="on">on</button>
<button id="off">off</button>
<script src="popup.js"></script>
</body>
</html>

Can I do tabs.sendMessage to specific tab?

For example, I have 3 tabs opened and the third tab is active. Can I "sendMessage" from the background script to the 1st tab(inactive)?
Also, how to do this, ".tabs.update"
I can do ".tabs.update" to the active tab by this,
browser.tabs.sendMessage(tabs[0].id, {
stat: "check"
}, function (response) {
browser.tabs.update(tabs[0].id, {
url: response.url
});
});
This sample sends to previously updated tabs every time a tab is updated.
const tabIds = {};
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") {
tabIds[tabId] = "";
for (const tabId in tabIds) {
console.log("sendMessage tabId=", tabId);
chrome.tabs.sendMessage(parseInt(tabId, 10), "hoge");
}
}
});

How to get and save images from cache - chrome extension

I would like to be able to download an image that has be cached by chrome to a specified folder using a chrome extension. Currently I am getting the url of the image and passing it to the background.js which then downloads the image. Yet on this specific website (the website this chrome extension is being built around), does not allow you to get the url of the image.
What changes to my code will I need to be able to do this?
(the extension flips to another page, and attempts to download around 50 images per subsection of the site. this site also does not have 1 class for each image, and regularly makes the class name or Id the token of the individual)
popup.js
const scriptCodeCollect =
`(function() {
// collect all images
let images = document.querySelectorAll('img');
let srcArray = Array.from(images).map(function(image) {
return image.currentSrc;
});
chrome.storage.local.get('savedImages', function(result) {
// remove empty images
imagestodownload = [];
for (img of srcArray) {
if (img) {
img.substring("data:image/".length, img.indexOf(";base64"));
console.log(img);
}imagestodownload.push(img);
};
result.savedImages = imagestodownload;
chrome.storage.local.set(result);
console.log("local collection setting success:"+result.savedImages.length);
});
})();`;
const scriptCodeDownload =
`(function() {
chrome.storage.local.get('savedImages', function(result) {
let message = {
"savedImages" : result.savedImages
};
chrome.runtime.sendMessage(message, function(){
console.log("sending success");
});
});
})();`;
function injectTheScript() {
// Gets all tabs that have the specified properties, or all tabs if no properties are specified (in our case we choose current active tab)
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// Injects JavaScript code into a page
chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"});
});
}
// adding listener to your button in popup window
document.getElementById('flipbtn').addEventListener('click', injectTheScript);
document.getElementById("startbtn").addEventListener("click", function() {
if((url.includes('http://127.0.0.1:5500/example%20test/physics/'))) {
document.getElementById("success").innerHTML = "<strong><u>In progress<br></u></strong> Currently downloading: <br>" +urlfilename
setInterval(function(){ //Loops download
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let urlfilename = tabs[0].url.replace('http://127.0.0.1:5500/example%20test/', '').replace('.html', '').replace('?','');
document.getElementById("success").innerHTML = "<strong><u>In progress<br></u></strong> Currently downloading: <br>" +urlfilename
let bknb= tabs[0].url.replace('http://127.0.0.1:5500/example%20test/', '').replace('.html', '').replace('/',' ').replace('?', '').replace(/\D/g, '');
chrome.storage.local.set({'foo': urlfilename, 'bar': bknb}, function() {
console.log('Settings saved');
console.log(urlfilename);
});
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
sleep(5000).then(() => { //Pauses so URL can write and display correctly
chrome.tabs.executeScript({code : scriptCodeCollect}); //Collects Image (page is saved as image on the website)
let textCollect = document.getElementById('textCollect');
chrome.storage.local.get('savedImages', function(result) {
textCollect.innerHTML = "collected "+ result.savedImages.length + " images";
});
});
chrome.tabs.executeScript({code : scriptCodeDownload}); //Downloads Image
document.getElementById("warning").innerHTML = "test"
sleep(5000).then(() => { //Waits so image can download fully
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"}); //Injects Script to flip page
});
});
});
}, 10000); //Waits 10s and then loops
background.js
let downloadsArray= [];
let initialState = {
'savedImages': downloadsArray
};
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
css: ['img'],
css: ['img[input[type="image"[aspect-ratio[attr(1000)/attr(1419)]]]]'],
css: ['id[image]']
})],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}]);
});
chrome.storage.local.set(initialState);
console.log("initialState set");
});
//chrome.downloads.onChanged.addListener(function() {
chrome.storage.local.get(['foo', 'bar'], function(items) {
var urlfilename = items.foo
console.log(urlfilename)
var bkpg= items.bar
// });
chrome.runtime.onMessage.addListener(
function(message, callback) {
console.log("message coming");
console.log(message);
let srcArray = message.savedImages;
var counter = bkpg-1;
for (let src of srcArray) {
console.log(src);
chrome.downloads.download({url:src, filename:urlfilename + ".png"});
};
});
});

Manifest v3 inject script from popup.js

In manifest v2 this code worked and injected the script when button was clicked:
popup.js v2 (works)
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
// Define button on click action
button.onclick = function () {
chrome.tabs.executeScript(null, {
file: 'Scripts/script.js'
});
window.close();
}
});
Now in manifest v3, chrome.tabs.executeScript is replaced with chrome.scripting.executeScript.
scripting permission is added in manifest.json.
popup.js v3 (not working)
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
// Define Scan button on click action
button.onclick = function () {
chrome.scripting.executeScript
(
{
target: { tabId: null}, // ???????
files: ['Scripts/script.js']
}
);
window.close();
}
});
The problem is that chrome.tabs.executeScript requires tabId value as one of the parameters.
How can I get tabId value in popup.js or convert the manifest v2 version javascript so that it works the same?
Thanks to #wOxxOm who posted a link as a comment.
The solution was to get the active tab and use its tabId.
document.addEventListener('DOMContentLoaded', function () {
// Get button by ID
var button = document.getElementById('btnScan');
button.onclick = injectScript;
});
async function injectScript() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['Scripts/script.js']
});
window.close();
}

How to prevent multiple dialog box in electron

I am opening some message boxes with electron's dialog.showMessageBox.
But it is currently opening multiple boxes. I would like to open only one message box at a time.
fetch(payload.url)
.then(res => res.json())
.then(data => {
download(BrowserWindow.getFocusedWindow(), data.presigned_url, {
saveAs: true,
// openFolderWhenDone: true,
showBadge: false,
filename: payload.filename
}).then(item => {
const filePath = item.getSavePath();
dialog.showMessageBox(
BrowserWindow.getFocusedWindow(),
{
type: 'info',
title: 'Download Status',
message: 'Download Complete',
buttons: ['Close', 'Open Folder', 'Open'],
},
dialogId => {
switch (dialogId) {
case 0:
break;
case 1:
shell.showItemInFolder(filePath);
break;
case 2:
shell.openItem(filePath);
default:
break;
}
},
);
});
});
For example, I would like to close last message box when a new one opens, OR just not allow opening next message box if one is already open.
Any form help would be appreciated.
In my project,
I give a state property, for e.g isOpenBrowseFileDialog and use it like a flag. If the dialog is launched, the flag is set to true and it will help to prevent open many dialogs.
browseFiles = async (e) => {
e.preventDefault();
const ref = this;
const { isOpenBrowseFileDialog } = this.state;
if(isOpenBrowseFileDialog === false) {
this.setState({
isOpenBrowseFileDialog: true
});
remote.dialog.showOpenDialog({
properties: ['openFile', 'multiSelections']
}, async (files) => {
if (files !== undefined) {
await ref.handleFilesAfterAdding(files);
}
ref.setState({
isOpenBrowseFileDialog: false
});
});
}
}

Categories