Mozilla Extension Alert every 30min - javascript

Hi i wanted to create extension that will trigger alert every 30mins to remind me check my posture. But i got stuck. I dont know how to make it so that alert triggers only in tab that im currently in. Now it triggers in every tab i have opened. Can someone help me please? Thanks.
As im thinking right now this way it will start new cycle every time i open new tab right? So im gonna see it in 30min only if i stay in that current tab.
setInterval(function() {
alert("Posture!");
}, 5000);
{
"name": "Posture Checker",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["posturecheck.js"]
}
]
}

You can check if a tab is in focus by checking if document.hidden.
if (document.hidden) {
// Document/tab/window is hidden
} else {
// Document/tab/window is visible
}
Alternatively, you can also check document.visibiliyState, but it does not return a boolean but a string value that you need to check against:
if (document.visibilityState === 'hidden') {
// Document/tab/window is hidden
} else if (document.visibilityState === 'visible') {
// Document/tab/window is visible
}

Related

refresh page until it changes chrome extension

i'm building extension for google chrome that refresh page until it changes its link.
I tried this code but it didn't worked:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (/^https:\/\/meet.google.com\/lookup/.test(changeInfo.url)) {
var intervalId = window.setInterval(function() {
var code = 'window.location.reload(); ';
chrome.tabs.executeScript(tab.id, {code: code});
}, 30000);
}
else {
window.clearInterval(intervalId)
}
});
i want to stop refresh when meet.google.com/lookup/ changes in another link, that could be also meet.google.com or meet.google.com/abcdef/.
So it refresh the page, but when the link of google meet changes, it keeps to refresh page. How can i solve? Thanks everyone!
P.S: I added my answer on a comment for be more understandable
I am assuming your aim is to keep refreshing a tab unless its location is meet.google...(the regex you have used), every thirty seconds.
If that is your aim, the problem here, is that the intervalID is lost once the event listener is executed. So, you need to maintain the intervalID outside of the listener scope so that you can clear it when that tab changes the URL.
I have the code below, try this
var intervalMap = {};
function handleUpdated(tabId, changeInfo, tabInfo) {
if (changeInfo.url) {
console.log("Tab: " + tabId + " URL changed to " + changeInfo.url);
if (changeInfo.url.indexOf("https://meet.google.com/?authuser") > -1) {
console.log("Found URL to reload. Added interval");
var intervalId = window.setInterval(function () {
var code = "window.location.reload(); ";
chrome.tabs.executeScript(tabId, { code: code });
}, 3000);
//Save the intervalId to our map
intervalMap[tabId] = intervalId;
} else if (intervalMap[tabId]) {
//Take interval ID from map and clear it
console.log("Tab changed to differente URL. Removed interval");
window.clearInterval(intervalMap[tabId]);
}
}
}
chrome.tabs.onUpdated.addListener(handleUpdated);
Manifest (Version 2)
{
"name": "Test",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": ["background.js"]
},
"permissions": ["background", "tabs", "https://meet.google.com/*"]
}
Edit: Have updated the code to add relevant console logs. Added manifest to ensure that required permissions are added

How can I start a function everytime the page loads?

(Sorry in advance if there are any english mistake)
Hi everyone, I'm working on a simple Chrome extension to edit some graphics and texts related fields of a website (Freshdesk) that I can't modify from the website itself because the code is proprietary.
My problem is, to make the function that replace the texts be active everytime the pages are displayed, I'm using a setInterval() with 100 ms of delay, which kinda does the job but it's not optimal, because the function runs like thousands of times in a few seconds.
function main() {
console.log('main started');
setInterval(changeText, 100); //(Not optimized)
}
function changeText() {
// replace 'Group' with 'Sector'' in the ticket tab visual
$('.ember-power-select-placeholder.label-field').each(function(x){
var new_text = $(this).text().replace("Group", "Sector");
$(this).text(new_text);
console.log('function started');
})
}
main();
As you can see from the screenshots and the code above, in this simple case I wanna change the text from
Group
to
Sector
and, as you can see, the code works, but if we take a look at the console.. (this is after like 5 seconds).
I already tried some function to make the js run as soon as the page loads just once, but none of them seem to work for me.
Do you have any tip to fix this situation?
EDIT: Here is the manifest.json too
{
"name": "DAN-Patch",
"version": "1.0",
"manifest_version": 2,
"permissions": [
"webNavigation",
"activeTab",
"background",
"tabs"
],
"content_scripts": [
{
"run_at": "document_idle",
"matches": ["https://gestionaledan.freshdesk.com/*", "https://gestionaledan.freshworks.com/*"],
"js": ["jquery-3.5.1.min.js", "content.js"],
"css": ["stylesheet.css"]
}
]
}
use this to reduce the number of processes:
function main() {
console.log('main started');
let exa = setInterval(function () {
let el = $('.ember-power-select-placeholder.label-field'),
all = 0;
el.each(function () {
if ($(this).text() == "Group") {
// replace 'Group' with 'Sector'' in the ticket tab visual
var new_text = $(this).text().replace("Group", "Sector");
$(this).text(new_text);
console.log('function started');
all ++;
}
});
if (all == 0) {
clearInterval(exa);
}
}, 100); //(Not optimized)
}
main();

jQuery select pre-exising button in chrome extension

I want to make an extension that changes the title on Chrome's built in stopwatch when i start and stop it. I am getting an error trying to retrieve the button's class. The JavaScript works when pasted in the browser console so I think the problem is with the json file.
Here is my JavaScript.
var title = document.querySelector("title");
var button = document.querySelector(".act-desktop-button");
var flip = true;
button.addEventListener("click", function(){
flip =! flip;
console.log(flip);
if(flip === true){
title.textContent = "OFF";
} else{
title.textContent = "ON";
}
});
and here is my json
{
"name": "Stopwatch Tracker",
"version": "1.0",
"description": "works with chromes built in stopwatch feature. Changes the
title of the page to 'ON' or 'OFF' depending on if the stopwatch is
running.",
"permissions":[
"tabs",
"*://*.google.com/search?q=stopwatch*"
],
"content_scripts": [
{
"matches": ["*://*.google.com/search?q=stopwatch*"],
"js": ["background.js"]
}
],
"manifest_version": 2
}
I am receiving this error:
I think, what is the most important part here is to make sure that you have checked the value of button to be not null before adding an event listener.
Just like this:
var button = document.querySelector(".act-desktop-button");
var flip = true;
if (button){
button.addEventListener("click", function(){
...
})};
Try also to check this SO post as this is related to your question.

Chrome extensions, change value of variable before executing script

I'm writing a simple chrome extension which on click inserts some text in Swedish in the DOM. Works fine. So whenever a user clicks the extension, the text in inserted.
Now I want to extend this a little bit. What I want to achieve:
1) When the user clicks the extension the first time, a text in Swedish is inserted
2) When the user clicks a second time, a text in English is inserted instead
So basically I want to "toggle" the language inserted between Swedish and English.
My manifest.json:
{
"name": "TextInserter",
"version": "1",
"manifest_version" : 2,
"description": "Inserts text",
"background" : {
"scripts" : ["background.js"],
"persistent": false
},
"permissions": ["activeTab"],
"browser_action": {}
}
The code in background.js:
chrome.tabs.executeScript(tab.id, {
code: 'var toggle = true;' // How can I toggle this value?
}, function() {
chrome.tabs.executeScript(tab.id, {file: 'content.js'});
});
The code in content.js:
var textarea = document.getElementById('description');
if (textarea && toggle) { // Is always true
textarea.value="Hej";
} else if (textarea && !toggle) {
textarea.value="Hello";
}
toggle = !toggle; // Change the value of toggle so next time text is inserted in other language
This of course doesn't work since I'm setting
var toggle = true;
in background.js.
How can I achieve this toggle effect?

Disable Extension on clicking the icon

I am trying to write a Chrome extension which can be disabled with a simple click on the browser action icon. I want to give the users this option because the extension raises a javascript alert when the alarm is triggered. The problem is that even after clearing the alarms, I am seeing alerts being raised. Also the icon click, which I want to work as a switch, isn't working as intended.
I have declared background.js as my background javascript file in manifest.json
"background": {
"scripts": ["alert.js"],
"persistent": true
},
"browser_action": {
"default_icon": "images/green.png",
"default_action": "popup.html",
"default_title": "Toggle Productiwitty"
}
background.js
var ExtensionOn = true;
function SwitchOn(e)
{
chrome.alarms.create("Alarm", {delayInMinutes: 0.1, periodInMinutes: 1} );
}
function SwitchOff(e)
{
chrome.alarms.clear("Alarm");
}
function showpopup()
{
alert("Inside function showpopup");
console.log("alert shown");
}
function click(e)
{
if(ExtensionOn)
{
SwitchOff();
console.log("switched off");
chrome.browserAction.setBadgeText({text: "Off"});
}
else if(!ExtensionOn)
{
SwitchOn();
console.log("switched on");
chrome.browserAction.setBadgeText({text: "ON"});
// Replace 15.0 with user selected time in minutes
}
//Toggle ExtensionOn
ExtensionOn = ~ ExtensionOn;
}
if(ExtensionOn)
{
chrome.alarms.onAlarm.addListener(showpopup);
}
chrome.browserAction.onClicked.addListener(click);
My "default_action": "popup.html" calls popup.js which creates the alarm
chrome.alarms.create("Alarm", {delayInMinutes: 0.1, periodInMinutes: 1} );
The idea is that once the extension is loaded, it should show a popup every 1 minute and if you click the icon, the extension gets disabled temporarily. On clicking the icon again, the same alert will be raised periodically.
ExtensionOn = true
> true
ExtensionOn = ~ ExtensionOn
> -2
Boolean(ExtensionOn)
> true
If you want to toggle a boolean, use !, not ~.
if(ExtensionOn)
{
chrome.alarms.onAlarm.addListener(showpopup);
}
This is only called once, when a page first loads. If the extension isn’t on at that time, the listener won’t be added, and the function will never be called. I’d recommend moving the if test into showpopup.
From https://developer.chrome.com/extensions/management#method-setEnabled
chrome.management.setEnabled(ExtId, true/false, callback)
But i'm not sure disabling the extension is what you actually want to do,
once you disable it you have to go to chrome://extension and manually re-enable it.

Categories