OPTIONS PAGE
// gets button from page
var checkButton = document.getElementById('saveCheck');
// initiates check fucntion when clicked
checkButton.addEventListener('click', check);
// starts when youtube setting is saved
function check() {
console.log('Check starts');
//initiates if checkbox is checked
if (check.checked) {
console.log('its checked');
localStorage.youtube = 1;
} else {
console.log('it isnt checked');
localStorage.youtube = 0;
}
}
console.log(localStorage.youtube);
This parts works perfectly, but when I try accessing the data stored in the local storage through my background.js page of my extension, it doesn't returns null for the values
BACKGROUND.JS
var ytcheck = localStorage.getItem('youtube');
console.log(ytcheck);
Related
I use Elementor Pro.
I have a button that is limited to 7 clicks, when clicking number 7 is disabled, and this is saved in localstorage to display later.
My problem if the user login from different device, the count start againg in 0. and obviously the code don't work for my need, The user after 7 click Never can click again.
How can resolve this?
this is the code:
<script>
// On page load (or in whatever event creates the button)
window.addEventListener("load", ()=>{
// Read the saved state from local storage (if not yet saved, will be null)
let clickcount3 = localStorage.getItem("localStorage.clickcount3");
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
});
function CounterMastPack() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount3) {
localStorage.clickcount3 = Number(localStorage.clickcount3)+1;
} else {
localStorage.clickcount3 = 1;
}
document.getElementById("resultMastPack").innerHTML = localStorage.clickcount3 + " Click(s).";
} else {
document.getElementById("resultMastPack").innerHTML = "Sorry, your browser does not support web storage...";
}
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
}
</script>
I want to disconnect all my users when the tab is closing or the browser is getting closed, so far so good. But when I refresh the page, all my users get disconnected too, this should not happen on refresh. Is it possible to avoid to execute this event on refresh? I saw some users doing with localStorage, but I still didn't get the point.
componentDidMount() {
this.beforeUnloadListener();
}
beforeUnloadListener = () => {
window.addEventListener("beforeunload", (ev) => {
ev.preventDefault();
// code to logout user
});
};
The way beforeunload works, you can not differentiate weather it's a page refresh or a browser close. beforeunload it is a quite confusing event avoid using this.
Hence for cases where you are dealing with the session you should use session storage. The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
Have done this on react application and its work for me on index.html file write this in script tag.
<script type="text/javascript">
window.addEventListener("beforeunload", (event) => {
window.localStorage.isMySessionActive = "true";
});
window.onunload = function (e) {
const newTabCount = localStorage.getItem("tabsOpen");
if (newTabCount !== null) {
localStorage.setItem("tabsOpen", newTabCount - 1);
}
};
</script>
Then go on main file and write this code.
useEffect(() => {
// define increment counter part
const tabsOpen = localStorage.getItem("tabsOpen");
if (tabsOpen == null) {
localStorage.setItem("tabsOpen", 1);
} else {
localStorage.setItem("tabsOpen", parseInt(tabsOpen) + parseInt(1));
}
// define decrement counter part
window.onunload = function (e) {
const newTabCount = localStorage.getItem("tabsOpen");
if (newTabCount !== null) {
localStorage.setItem("tabsOpen", newTabCount - 1);
}
};
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
window.localStorage.isMySessionActive = "false";
} else {
const newTabCount2 = localStorage.getItem("tabsOpen");
let value = localStorage.getItem("isMySessionActive");
if (value == "true") {
if (newTabCount2 - 1 == 0) {
localStorage.clear();
window.localStorage.isMySessionActive = "false";
} else {
window.localStorage.isMySessionActive = "false";
}
}
}
}, []);
I'm struggling to add cookie control to my popup so it only shows once.
var modal = document.querySelector(".modal");
var close = document.getElementById("myDiv");
var element = document.getElementById("myDiv");
function popupScroll() {
element.classList.add("show-modal");
}
function closeModal() {
element.classList.add("hide-modal");
}
window.addEventListener("scroll", popupScroll);
window.addEventListener("click", closeModal);
You could use localStorage or sessionStorage.
While localStorage accesses the current domain's local Storage object and adds a data item to it, sessionStorageaccesses the current domain's session Storage object and adds a data item to it.
var modal = document.querySelector(".modal");
var close = document.getElementById("myDiv");
var element = document.getElementById("myDiv");
function popupScroll() {
if (!localStorage.getItem('showPopup')) { //check if popup has already been shown, if not then proceed
localStorage.setItem('showPopup', 'true'); // Set the flag in localStorage
element.classList.add("show-modal");
}
}
function closeModal() {
element.classList.add("hide-modal");
}
window.addEventListener("scroll", popupScroll);
window.addEventListener("click", closeModal);
Remember, while an item that has been set in sessionStorage lasts as long your browser session, the localStorage items don't have expiration times. That being said, in your current case, you could use either localStorage or sessionStorage.
I advice to use localStorage. Its a Javascript API with functions like setItem and getItem. Here an example:
function displayPopup() {
//if the variable in localStorage is set dont show the popup and just return
if (localStorage.getItem('popupAlreadyShown')) return;
//display popup, example:
document.getElementById('popup').style.display = 'block';
}
function closePopup() {
//close popup, example:
document.getElementById('popup').style.display = 'none';
//set the variable in localStorage that the popup is closed
localStorage.setItem('popupAlreadyShown', 'true');
}
I am new to chrome extension making.I was trying to store data in local storage and retrive from it. But as I put retrieve in content script it runs that before data is saved in local storage. So I was trying to make chrome.storage.local.get as a conditional. To check either it works or not I have added alert. After getting into get section it generates the alert continuously. It does not go next line.I tried both quoted undefined and nonquoted undefined.
Here is my content_script.js code:
var message;
function bodyHandler(e){
if (e.type == 'mousemove'){
chrome.storage.local.get('word', function(data) {
alert("from get");
if(typeof data.word !== undefined){
message = chrome.storage.local.get('word');
alert("from if");
}
else{
alert("from else");
message ="Hello!";
}
})
var paragraph = document.getElementsByTagName('p');
for(var i=0; i < paragraph.length; i++){
//alert('hello.');
paragraph[i].innerHTML = message;
}
}
}
document.body.addEventListener('mousemove', bodyHandler, false);
Here is my popup.js:
var evnt = document.getElementById("clicked");
function wordGetter(){
var txt= document.getElementById("wordinput").value;
chrome.storage.local.set({'word': txt});
}
evnt.addEventListener('click', wordGetter);
I cannot understand why alert("from get") is running continuously.
I am making a chrome extension to keep refreshing a page unless stop button is chosen. But i am able to do it only once. Here is my code for background.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch(request.type) {
case "table-row-count_start":
alert("Refershing started");
RefreshAndCount();
break;
case "table-row-count_stop":
alert("Stop Refershing");
break;
}
return true;
});
var RefreshAndCount = function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "table-row-count"});
chrome.browserAction.setBadgeText({tabId: tabs[0].id, text: "Counting!"});
});
};
In content.js I did this :
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
alert(message.type);
switch(message.type) {
case "table-row-count":
var x = document.querySelector('table').rows.length;
chrome.storage.sync.set({'value': x}, function() {
console.log('Settings saved');
});
chrome.storage.sync.get(["value"], function(items){
console.log(items);
});
alert("Row count = " + x);
setTimeout(function(){
location.reload();
},100);
break;
}
});
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (key in changes) {
if(key=='value'){
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
}
});
After refresh I want to print the current row count alert everytime. Please help how to do this .
This work fine, for a single refresh but after that I again had to choose the start button from popup.
I want some way that I need not click start button again and the whole process repeats, storing the previous row count in cache or something.
popup.js
window.onload = function() {
document.getElementById("mystartbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_start"
});
}
document.getElementById("mystopbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_stop"
});
}
}
Also help me How to keep on refershing that page even if I switch to other tab or minimise my chrome ?
You can use the chrome.storage.local to store data that will be saved over time and over context where you use it. You can set a boolean to true or false to enable or disable autoreload. Then you only have to set it at click on browser action and check it in the content-script to know if you have to reload.
A possible and simple implemtation should be like this : (It depends of the expected behavior)
content.js (have to be injected in the page to autoreload)
var reloadDuration = 5000;
function autoreload()
{
chrome.local.storage.get("autoreload_enabled", function(result)
{
if(result.autoreload_enabled)
{
chrome.runtime.sendMessage({type: "table-row-count"});
window.location.reload();
}
}
}
setTimeout(autoreload, reloadDuration);
This will reload your page every reloadDuration if the boolean set in chrome local storage named autoreload_enabled is true.