How to dynamically change the version from package.json? - node.js

I get version 1.0.1 (server_version) from the server
I compare what is in process.env.version === server_version
If this is the case, then I change process.env.version = server_version.
However, I just can't do it from the client side.
All this is needed to request an update from the user, that is, when a new version is released, then ask, and then do $router.go()

If you're using Vue-CLI - you can do the same as me:
// vue.config.js
module.exports =
{
chainWebpack: config =>
{
config.plugin('define')
.tap(args =>
{
args[0]['process.env'].BUILD_TIME = webpack.DefinePlugin.runtimeValue(Date.now, ['./package.json']);
args[0]['process.env'].VERSION = JSON.stringify(pk.version);
return args;
});
return config;
}
}
Then, in your public/index.html
<!DOCTYPE html>
<html>
<head>
.....
<template id="VERSION"><%= process.env.VERSION %></template>
.....
</html>
Then, in your src/main.js
import mixinVersion from './mixins/mixinVersion'
import { version } from '../package.json'
.....
new Vue({
mixins: [mixinVersion],
computed:
{
appVersion()
{
const buildTime = new Date(process.env.BUILD_TIME);
return version + ' (' + buildTime.toLocaleString('en', {
year: 'numeric',
day: 'numeric',
month: 'short',
hour: 'numeric',
minute: 'numeric',
}) + ')';
},
},
created()
{
this.firstVersionCheck();
}
});
Then in src/mixins/mixinVersion.js
import { version } from '#/../package.json';
const checkingPeriod = 200; // in seconds
function isNewerVersion(_old, _new)
{
// return true if SemVersion A is newer than B
const oldVer = _old.split('.');
const newVer = _new.split('.');
if (+oldVer[0] < +newVer[0]) return false;
if (+oldVer[0] > +newVer[0]) return true;
if (+oldVer[1] < +newVer[1]) return false;
if (+oldVer[1] > +newVer[1]) return true;
return +oldVer[2] > +newVer[2];
}
export default
{
data()
{
return {
newVersionExists: false,
timerVersion: null,
lastVersionCheck: null,
windowHiddenProp: '',
};
},
watch:
{
newVersionExists(newVal, oldVal)
{
// if the user decides to dismiss and not refresh - we must continue checking
if (oldVal && !newVal) this.scheduleVersion();
},
},
methods:
{
firstVersionCheck()
{
this.lastVersionCheck = Date.now();
// Set the name of the hidden property and the change event for visibility
let visibilityChange;
if (typeof document.hidden !== 'undefined')
{
// Opera 12.10 and Firefox 18 and later support
this.windowHiddenProp = 'hidden';
visibilityChange = 'visibilitychange';
}
else if (typeof document.msHidden !== 'undefined')
{
this.windowHiddenProp = 'msHidden';
visibilityChange = 'msvisibilitychange';
}
else if (typeof document.webkitHidden !== 'undefined')
{
this.windowHiddenProp = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
document.addEventListener(visibilityChange, this.handlePageVisibility, false);
this.scheduleVersion();
},
handlePageVisibility()
{
if (!document[this.windowHiddenProp])
{
// if too much time has passed in the background - immediately check for new version
if (Date.now() - this.lastVersionCheck > checkingPeriod * 1000)
{
if (this.timerVersion) clearTimeout(this.timerVersion);
this.checkVersion();
}
}
},
scheduleVersion()
{
// check for new versions
if (this.timerVersion) clearTimeout(this.timerVersion);
this.timerVersion = setTimeout(this.checkVersion, checkingPeriod * 1000); // check for new version every 3.3 minutes
},
checkVersion()
{
this.timerVersion = null;
fetch(process.env.BASE_URL + 'index.html', {
headers:
{
'X-SRS-Version': version,
}
}).then(response =>
{
if (response.status != 200) throw new Error('HTTP status = ' + response.status);
return response.text();
}).then(t =>
{
this.lastVersionCheck = Date.now();
const newVersion = t.match(/<template id="?VERSION"?>([^<]+)<\/template>/);
if (newVersion && newVersion[1])
{
if (isNewerVersion(newVersion[1], version))
{
if (!this.newVersionExists) // do not show multiple notifications
{
this.$snotify.confirm('There is a new version', 'New version', {
timeout: 0,
closeOnClick: false,
position: 'leftBottom',
buttons:
[
{
text: 'REFRESH',
action()
{
window.location.reload();
}
}
]
});
}
this.newVersionExists = true;
}
else this.scheduleVersion();
}
else this.scheduleVersion();
}).catch(err =>
{
if (navigator.onLine) console.error('Could not check for new version', err.message || err);
this.scheduleVersion();
});
},
}
};

Related

How to implement Gpay payment gateway in NodeJS?

I tried it in html and javascript it's working perfect in web (mobile's browser).I am using angular for frontend and node for backend but not getting any solution for redirect Playstore or Gpay for mobile browser. Basically I want to implement for mobile browser.
this is my node for backend code & for frontend I already paste static--
const canMakePaymentCache = 'canMakePaymentCache';
onBuyClicked();
function readSupportedInstruments() {
let formValue = {};
formValue['pa'] = keys.GPAY_MERCHANT_ID;//merchantId
formValue['pn'] = `Test_Gpay_Name`;//transactionId
formValue['tn'] = 'Testing Messages ';//message
formValue['mc'] = 'merchant Code';//
formValue['tr'] = 'Transaction Reference';
formValue['tid'] = 'Transaction id';
formValue['url'] = 'http://localhost.co/';
return formValue;
}
function readAmount() {
//const pay_amount = parseInt(req.body.amount) * 100;
return parseInt(req.body.amount) * 100;
}
function onBuyClicked() {
// if (!window.PaymentRequest) {
// console.log('Web payments are not supported in this browser.');
// return;
// }
let formValue = readSupportedInstruments();
const supportedInstruments = [
{
supportedMethods: ['https://pwp-server.appspot.com/pay-dev'],
data: formValue,
},
{
supportedMethods: ['https://tez.google.com/pay'],
data: formValue,
},
];
const details = {
total: {
label: 'Total',
amount: {
currency: 'INR',
value: readAmount(),
},
},
displayItems: [
{
label: 'Original amount',
amount: {
currency: 'INR',
value: readAmount(),
},
},
],
};
const options = {
requestShipping: false,
requestPayerName: false,
requestPayerPhone: false,
requestPayerEmail: false,
shippingType: 'shipping',
};
let request = null;
try {
//const PaymentRequest = {};
//request = PaymentRequest(supportedInstruments, details, options);
request ={supportedInstruments, details, options};
} catch (e) {
return;
}
if (!request) {
console.log('Web payments are not supported in this browser.');
return;
}
var canMakePaymentPromise = checkCanMakePayment(request);
canMakePaymentPromise
.then((result) => {
showPaymentUI(request, result);
})
.catch((err) => {
console.log('Error calling checkCanMakePayment: ' + err);
});
}
function checkCanMakePayment(request) {
//if (sessionStorage.hasOwnProperty(canMakePaymentCache)) {
//return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
//}
var canMakePaymentPromise = Promise.resolve(true);
if (request.canMakePayment) {
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then((result) => {
canMakePaymentCache = result;
return result;
})
.catch((err) => {
console.log('Error calling canMakePayment: ' + err);
});
}
function showPaymentUI(request, canMakePayment) {
if (!canMakePayment) {
redirectToPlayStore();
return;
}
let paymentTimeout = window.setTimeout(function () {
window.clearTimeout(paymentTimeout);
request.abort()
.then(function () {
console.log('Payment timed out after 20 minutes.');
})
.catch(function () {
console.log('Unable to abort, user is in the process of paying.');
});
}, 20 * 60 * 1000); /* 20 minutes */
request.show()
.then(function (instrument) {
window.clearTimeout(paymentTimeout);
processResponse(instrument); // Handle response from browser.
})
.catch(function (err) {
console.log(err);
});
}
function processResponse(instrument) {
var instrumentString = instrumentToJsonString(instrument);
console.log(instrumentString);
fetch('/buy', {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: instrumentString,
credentials: 'include',
})
.then(function (buyResult) {
if (buyResult.ok) {
return buyResult.json();
}
console.log('Error sending instrument to server.');
})
.then(function (buyResultJson) {
completePayment(
instrument, buyResultJson.status, buyResultJson.message);
})
.catch(function (err) {
console.log('Unable to process payment. ' + err);
});
}
function completePayment(instrument, result, msg) {
instrument.complete(result)
.then(function () {
console.log('Payment completes.');
console.log(msg);
document.getElementById('inputSection').style.display = 'none'
document.getElementById('outputSection').style.display = 'block'
document.getElementById('response').innerHTML =
JSON.stringify(instrument, undefined, 2);
})
.catch(function (err) {
console.log(err);
});
}
console.log(`in line 448....`);
function redirectToPlayStore() {
//if (confirm('Tez not installed, go to play store and install?')) {
//window.location.href = 'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha'
//res.writeHead( "https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha" );
const response_data = axios
.post(
'https://play.google.com/store/apps/details?id=com.google.android.apps.nbu.paisa.user.alpha',
)
console.log(`in line no. 459... ${response_data}`);
return response_data;
//};
}
function instrumentToJsonString(instrument) {
var instrumentDictionary = {
methodName: instrument.methodName,
details: instrument.details,
shippingAddress: addressToJsonString(instrument.shippingAddress),
shippingOption: instrument.shippingOption,
payerName: instrument.payerName,
payerPhone: instrument.payerPhone,
payerEmail: instrument.payerEmail,
};
return JSON.stringify(instrumentDictionary, undefined, 2);
}

In component data is fetched only when i make some changes in it

I am trying to add markers on map, using a view and component
In view where i call an api and then i pass that data to component using v:bind but console.log in that component shows an empty array, when i make some changes in that component the page reloads and data is fetched following is my code in view and then component.
//Script for View
<script>
import Maps from '../components/Maps.vue';
import LoadingOverlay from '../components/loading.vue';
import MessageHelper from '../helpers/messageHelper';
import RepositoryFactory from '../repositories/RepositoryFactory';
const Catalogs = RepositoryFactory.get('catalogs');
export default {
components: {
Maps,
LoadingOverlay,
},
data() {
return {
zones_and_locations: [],
loadingConfig: {
isLoading: true,
cancellable: true,
onCancelMessage: this.onCancelMessage(),
isFullPage: true,
},
};
},
created() {
this.fetchPlacesData();
},
methods: {
async fetchPlacesData() {
const { data } = await Catalogs.getZoneLocations();
if (data.output === null) {
this.nullDataException();
} else {
const places = [];
data.output.forEach((value, index) => {
places.push(value);
});
this.zones_and_locations = places;
this.loadingConfig.isLoading = false;
}
},
onCancelMessage() {
return MessageHelper.getLoadingCancelMessage();
},
nullDataException() {
this.exceptionMessage = 'Data from API is not available.';
console.log(this.exceptionMessage);
},
},
};
</script>
//Script For Map.vue
<script>
import MarkerClusterer from '#google/markerclusterer';
import GoogleMapsHelper from '../helpers/GoogleMapsHelper';
export default {
name: 'GoogleMap',
props: ['zones_and_locations'],
data() {
return {
country: '',
markers: [],
map: '',
};
},
created() {
this.loadGoogleMaps();
},
methods: {
markerClusterer(map, markers) {
return new MarkerClusterer(
map,
markers,
{ imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' },
);
},
async loadGoogleMaps() {
try {
const google = await GoogleMapsHelper();
const geoCoder = new google.maps.Geocoder();
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
mapTypeControl: false,
fullscreenControl: false,
});
geoCoder.geocode({ address: 'Singapore' }, (results, status) => {
if (status !== 'OK' || !results[0]) {
throw new Error(status);
}
// set Center of Map
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
});
this.map = map;
let zones = [];
Array.prototype.forEach.call(this.zones_and_locations, child => {
var obj = {
lat: parseFloat(child.lat),
lng: parseFloat(child.lng),
}
var position = {
position: obj,
};
zones.push(position);
});
if (zones.length > 0) {
const markers = zones.map(x => new google.maps.Marker({ ...x, map }));
this.markerClusterer(map, markers);
}
} catch (error) {
console.error(error);
}
},
},
};
</script>
//Template for View
<template>
<div>
<!-- START::Loading Overlay -->
<LoadingOverlay
v-bind:loadingConfig="loadingConfig">
</LoadingOverlay><!-- END::Loading Overlay -->
<Maps v-bind:zones_and_locations="zones_and_locations"
></Maps>
</div>
</template>
//Template for Component
<template>
<div>
<div id="map" class="google-map"></div>
</div>
</template>
Data from the parent component are loaded asynchronously, so the created lifecycle hook inside the component is executed before the actual data comes, when they're still set as an empty array and are not reactive to change.
You can fix this by setting a watch inside the component, like this:
methods: {
...
},
watch: {
zones_and_locations (newVal, oldVal) {
this.loadGoogleMaps();
}
}
orelse you can set a reference to the child component and invoke its method when data comes:
<!-- main view -->
<Maps
v-bind:zones_and_locations="zones_and_locations"
ref="myMap"
></Maps>
async fetchPlacesData() {
const { data } = await Catalogs.getZoneLocations();
if (data.output === null) {
this.nullDataException();
} else {
const places = [];
data.output.forEach((value, index) => {
places.push(value);
});
this.zones_and_locations = places;
// using $refs
this.$refs.myMap.loadGoogleMaps();
this.loadingConfig.isLoading = false;
}
},

How to create Pagination with vue-table2?

I'm using the Vue-table2 for rendering the table. https://github.com/ratiw/vuetable-2
<vuetable ref="vuetable"
:api-url= "apiurl"
:fields="fields">
</vuetable>
My Server Api Response doesn't have any Pagination response in it . The data returned by server is
{
"data":[
{
"id":22535,
"message":"Message1",
"message_type":"tag1",
"time":"2018-08-13T14:41:57Z",
"username":"rahuln"
},
{
"id":22534,
"message":"Message2",
"message_type":"tag2",
"time":"2018-08-13T14:02:27Z",
"username":"govindp"
},
..................
],
"error":null,
"success":true
}
This is the first time I'm Using Vue-js. How can i add the pagination into it and still using vue-table2.
Thanks In advance.
Since you don't have pagination values you must insert it we gonna trick vue-table like this
<template>
<div>
<vuetable ref="vuetable" api-url="/api/ahmed" :fields="fields" pagination-path="" #vuetable:pagination-data="onPaginationData" #vuetable:load-success="loadSuccess">
</vuetable>
<vuetable-pagination ref="pagination" #vuetable-pagination:change-page="onChangePage"></vuetable-pagination>
</div>
</template>
<script>
import Vuetable from 'vuetable-2/src/components/Vuetable'
import VuetablePagination from 'vuetable-2/src/components/VuetablePagination'
export default {
components: {
Vuetable,
VuetablePagination,
},
data() {
return {
fields: ['name', 'email', 'birthdate', 'nickname', 'gender', '__slot:actions'],
allData: false,
currentPage: 1,
}
},
mounted() {
},
methods: {
onPaginationData(paginationData) {
this.$refs.pagination.setPaginationData(paginationData)
},
loadSuccess(data) {
this.$refs.vuetable.$nextTick(()=>{
if (!this.allData) {
this.allData = data;
}
if (!data.data.per_page) {
data = this.setData(this.currentPage);
this.$refs.vuetable.loadSuccess(data);
}
})
},
setData(Page) {
var data = JSON.parse(JSON.stringify(this.allData));
var total = data.data.data.length;
var perPage = 10;
var currentPage = Page;
var lastPage = parseInt(total / perPage) + ((total % perPage) === 0 ? 0 : 1)
var from = parseInt((currentPage - 1) * perPage) + 1;
var to = from + perPage - 1;
to = to > total ? total : to;
console.log(from,to)
var newData = this.allData.data.data.filter(function(element, index) {
if (index >= from-1 && index <= to-1) {
console.log(index,from,to)
return true;
}
return false;
})
// console.log(newData)
// return newData;
data.data = {
"total": total,
"per_page": perPage,
"current_page": currentPage,
"last_page": lastPage,
"next_page_url": "",
"prev_page_url": null,
"from": from,
"to": to,
data: newData
}
// console.log(data)
this.currentPage = Page;
this.$refs.vuetable.loadSuccess(data);
return data;
},
onChangePage(page) {
this.setData(page);
}
}
}
</script>

Angular 4 Getting 404 not found in production mode

I'm building an angular node app and am doing a http post request to signup a user. Its a chain of observables that gets the users social login information, signs ups the user, then on success emails the user. In dev mode everything works perfect, in prod mode, im getting a 404 not found. I also want to note that in development mode, some of my function calls in the observables on success are not being called. Its acting very strange and cannot figure out what I am doing wrong.
Here is my route controller
module.exports = {
signup: function signup(req, res) {
return User.create({
email: (req.body.email).toLowerCase(),
image: req.body.image,
name: req.body.name,
provider: req.body.provider || 'rent',
uid: req.body.uid || null
}).then(function (user) {
return res.status(200).json({
title: "User signed up successfully",
obj: user
});
}).catch(function (error) {
console.log(error);
return res.status(400).json({
title: 'There was an error signing up!',
error: error
});
});
}
};
and route
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
My service
#Injectable()
export class UserService {
private devUrl = 'http://localhost:3000/user';
private url = '/user';
sub: any;
public user: User;
constructor(
private authS: AuthService,
private http: HttpClient) {
}
signup(user: User) {
return this.http.post(this.url + '/signup', user);
}
auth(provider: string) {
return this.sub = this.authS.login(provider);
}
logout() {
this.authS.logout()
.subscribe(value => {
console.log(value);
}, error => console.log(error))
}
getUser() {
return this.user;
}
}
and my component logic for signing up using social buttons
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
Here is the whole component
import {Component, DoCheck, HostListener, OnInit} from '#angular/core';
import {User} from "../user/user.model";
import {UserService} from "../user/user.service";
import {UiService} from "../ui.service";
import {ContactService} from "../contact/contact.service";
import {Email} from "../contact/email.model";
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.component.html',
styleUrls: ['./landing-page.component.css']
})
export class LandingPageComponent implements OnInit, DoCheck {
user: User = {
email: '',
image: '',
name: '',
provider: '',
uid: ''
};
signupComplete = false;
signup = false;
contact = false;
error = false;
errorStr = 'There was an error';
checkmark = false;
thankyou = false;
randomNum = Math.floor(Math.random() * 2);
#HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
const enter = 13;
if (event.keyCode === enter) {
// this.onSignup();
}
}
constructor(
private uis: UiService,
private contactS: ContactService,
private userService: UserService) { }
ngOnInit() {}
ngDoCheck() {
this.signup = this.uis.onGetSignup();
this.contact = this.uis.onGetContact();
this.signupComplete = this.uis.onReturnSignupComplete();
this.error = this.uis.getError();
this.errorStr = this.uis.getErrorStr();
}
onClickAction(s: string) {
this.uis.onClickAction(s);
}
onSignup() {
this.user.provider = 'rent';
this.user.uid = null;
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.contactS.setEmail(email)
.subscribe(email => {
this.onReset();
}
, error => console.log(error));
}, response => {
if (response.error['error'].errors[0].message === 'email must be unique') {
this.uis.onSetError('Email is already used');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
} else {
this.uis.onSetError('There was an error');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
}
});
}
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
onReset() {
this.user.email = '';
this.user.image = '';
this.user.name = '';
this.user.provider = '';
this.user.uid = '';
}
errorStyle(): Object {
if (this.error) {
return {height: '50px', opacity: '1'};
} else if (!this.error) {
return {height: '0', opacity: '0'};
}
return {};
}
}
I want to mention I am using angular-2-social-login for the social logins. Unsure why it would be calling 404 if I am using the /user/signup route appropriately.

return value of chrome.webRequest based chrome.storage

Save and restore options!
I'm trying to block some sites through WebRequest, but when the ckeckbox this false even still blocking the site, anyone can help, this is the code that I have
Options.js
function save_options(){
var blockurl_1 = document.getElementById("blockurl_1").checked;
var blockurl_2 = document.getElementById("blockurl_2").checked;
chrome.storage.sync.set({
blockurl_1: blockurl_1,
blockurl_2: blockurl_2
}, function() {
var status = document.getElementById('status');
status.textContent = 'Block';
});
}
function restore_options() {
chrome.storage.sync.get({
blockurl_1: false,
blockurl_2: false
}, function(items) {
document.getElementById('blockurl_1').checked = items.blockurl_1;
document.getElementById('blockurl_2').checked = items.blockurl_2;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
var checkcontent = document.getElementsByClassName("save")[0];
checkcontent.addEventListener("click",save_options);
I need to do this myself, but with chrome.storage
chrome.webRequest.onBeforeRequest.addListener(function(details) {
return {
cancel: ( localStorage["block_chat_seen"] == 'true' ) ? true : false
}
}, { urls: ['*://*.facebook.com/'] }, ['blocking'])
...
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
chrome.storage.sync.get(null, function(items) {
if (items.blockurl_1) {
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var state = (blockurl_1 === true) ? 'true' : 'false';
return { cancel: state }; }, {
urls: ["*://www.google.com.co/*"]
},
["blocking"]);
}
if (items.blockurl_2) {
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var state = (blockurl_2 === true) ? 'true' : 'false';
return { cancel: state }; }, {
urls: ["*://www.youtube.com.co/*"]
},
["blocking"]);
}
});
});
You are adding listeners each time.
You need to clear existing ones before adding a new one.

Resources