Can I use jquery deferreds to sequentially show jquery ui dialogs - dialog

I am trying to use JQuery UI Dialog with JQuery deferreds to sequentially show two dialogs. However, it seems that the dialog code is executed immediately for the first dialog and then the second dialog appears.
I have this JSFiddle snippet:
http://jsfiddle.net/clee/db5SX/179/
Is what I'm attempting to do not feasible since the invocation of the dialog is synchronous?
code here:
var deferred = new $.Deferred();
function step1() {
var d1 = new $.Deferred();
var options = {
modal: true,
width: 400,
title: "dialog 1",
buttons: [
{
'text':'ok',
'click': function () {
console.log('ok');
d1.resolve(true);
$(this).dialog('close');
}
},
{
'text':'cancel',
'click': function () {
console.log('cancel');
d1.reject();
$(this).dialog('close');
}
}
]
};
$("#dialog").dialog(options);
return d1.promise();
}
function step2() {
var d1 = new $.Deferred();
var options = {
modal: true,
width: 400,
title: "dialog 2",
buttons: [
{
'text':'ok',
'click': function () {
console.log('ok');
d1.resolve(true);
$(this).dialog('close');
}
},
{
'text':'cancel',
'click': function () {
console.log('cancel');
d1.reject();
$(this).dialog('close');
}
}
]
};
$("#dialog").dialog(options);
return d1.promise();
}
deferred.then(function(){step1();}).then(function(){step2();});
var deferred = new $.Deferred();
function step1() {
var d1 = new $.Deferred();
var options = {
modal: true,
width: 400,
title: "dialog 1",
buttons: [
{
'text':'ok',
'click': function () {
console.log('ok');
d1.resolve(true);
$(this).dialog('close');
}
},
{
'text':'cancel',
'click': function () {
console.log('cancel');
d1.reject();
$(this).dialog('close');
}
}
]
};
$("#dialog").dialog(options);
return d1.promise();
}
function step2() {
var d1 = new $.Deferred();
var options = {
modal: true,
width: 400,
title: "dialog 2",
buttons: [
{
'text':'ok',
'click': function () {
console.log('ok');
d1.resolve(true);
$(this).dialog('close');
}
},
{
'text':'cancel',
'click': function () {
console.log('cancel');
d1.reject();
$(this).dialog('close');
}
}
]
};
$("#dialog").dialog(options);
return d1.promise();
}
deferred.then(function(){step1();}).then(function(){step2();});
deferred.resolve();

Related

How to block the url chrome://extension and new tab in my extension with manifest v3?

My google chrome extension has a background.js and content script that communicate with port.OnMessage but I have noticed that when I run my extension in Chrome://extension it throws an error because it is not a url and the same happens with a new google tab chrome which has no url. How could I block them?
On the internet I got information that said that they were blocked with
"exclude_matches": [
"chrome://extensions/"
]
however, this doesn't work for the version 3 manifest. Also how could it tell you not to run the extension in a new tab (no url)
this is my manifest v3
"name":"Certified Records Full Certificate",
"description":"Esta extensión permite grabar la pantalla o hacer capturas de pantalla",
"version": "1.0",
"manifest_version":3,
"background":{
"service_worker":"background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-script.js"],
"exclude_matches": [
"chrome://extensions/"
]
}],
"permissions":["storage","activeTab","scripting","tabs","desktopCapture"],
"action":{
"default_popup":"popup.html",
"default_icon":{
"16":"/images/logo-16.png",
"32":"/images/logo-32.png",
"48": "/images/logo-48.png",
"128": "/images/logo-128.png"
}
},
"icons":{
"16":"/images/logo-16.png",
"32":"/images/logo-32.png",
"48": "/images/logo-48.png",
"128": "/images/logo-128.png"
} }
this is my background.js
chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(function(msg){
if (msg.type === 'SS_UI_REQUEST') {
requestScreenSharing(port,msg);
}
});
});
function requestScreenSharing(port, msg) {
const sources = ['window'];
const tab = port.sender.tab;
desktopMediaRequestId = chrome.desktopCapture.chooseDesktopMedia(
sources,
port.sender.tab,
streamId => {
if (streamId) {
msg.type = 'SS_DIALOG_SUCCESS';
msg.streamId = streamId;
msg.text ="sharing";
} else {
msg.type = 'SS_DIALOG_CANCEL';
msg.text ="cancel";
}
var tab = getTabId();
tab.then((value) => {
const respuesta = chrome.tabs.connect(value.id, {
name: "respuesta",
});
respuesta.postMessage(msg);
});
}
);
}
async function getTabId() {
let queryOptions = { active: true, currentWindow: true };
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}
this is my content-script.js
chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(function(msg){
if (msg.type === 'SS_UI_REQUEST') {
console.log(msg);
var background = chrome.runtime.connect();
background.postMessage(msg);
}
if (msg.type === 'SS_DIALOG_SUCCESS') {
console.log(msg);
startScreenStreamFrom(msg.streamId);
}
if (msg.type === 'SS_DIALOG_CANCEL') {
console.log(msg);
}
if(msg.type === "SS_UI_TAKESCREENSHOT")
{
console.log("tomar screenshot");
TakeScreenShot();
}
});
});
function startScreenStreamFrom(streamId) {
console.log("compartiendo pantalla");
navigator.mediaDevices
.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: streamId
}
}
})
.then(stream => {
window.stream = stream;
});
}
async function TakeScreenShot(){
setTimeout(async () => {
const screen = window.stream;
const track = screen.getVideoTracks()[0];
const imageCapture = new ImageCapture(track);
await imageCapture.grabFrame()
.then(function(bitmap) {
track.stop();
var canvas = document.createElement('canvas');
canvas.width = bitmap.width
canvas.height = bitmap.height
const context = canvas.getContext('2d')
context.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height)
const image = canvas.toDataURL()
var link = document.createElement('a');
link.download = 'FullCertificateCaptureScreen.png';
link.href = image
link.click();
})
.catch(function(error) {
track.stop();
console.log('grabFrame() error: ', error);
});
}, 1000);
}
this is the popup script
document.getElementById("btn-share").addEventListener("click", function(){
var tab = getTabId();
tab.then((value) => {
chrome.storage.local.set({'pestaña': value.id});
const port = chrome.tabs.connect(value.id, {
name: "conexion",
});
port.postMessage({ type: 'SS_UI_REQUEST', text: 'start' }, '*');
}); //fin de tab.then()
})//fin de click addEventListener
document.getElementById("btn-capture").addEventListener("click", async function(){
chrome.storage.local.get('pestaña', function (result) {
const port = chrome.tabs.connect(result.pestaña, {
name: "tomarScreenShot",
});
port.postMessage({ type: 'SS_UI_TAKESCREENSHOT', text: 'takescreenshot' }, '*');
window.close();
});
});
async function getTabId() {
let queryOptions = { active: true, currentWindow: true };
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}

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;
}
},

custom element error in jointjs when use vue-cli

I got an error when use my element in vue-cli.
I do not why joint.shapes do not contain my element!
test.vue:
// Cannot read property 'Component' of undefined"
<script>
const joint = require('jointjs');
joint.dia.Element.define('example.Component', {
attrs: {
...
},
}, {
markup: ...,
}, {
createComponent: function() {
return new this({
attrs:{
...
}
});
}
});
export default {
name: "FlowCanvas",
mounted() {
var graph=new joint.dia.Graph;
var paper = new joint.dia.Paper({
...
});
var el1=joint.shapes.example.Component.createComponent();
el1.position(100,100);
},
}
</script>

call function from same class nodejs

I try to call function from same class but it always return an error TypeError: this.c is not a function I tried also module.exports.c() and the same result
module.exports = (options)=>{
return{
a:(a)=>{
console.log(a);
},
b:(b)=>{
this.c('c');
console.log(b)
},
c:(c)=>{
console.log(c);
}
}
}
After Updated
module.exports = ({})=>{
return{
genereate:function(identifier){
console.log('genereate')
},
middleware:function(req,res,next){
this.c();
console.log('genereate')
},
c:function(){
console.log('geeet');
}
}
}
Arrow functions bind this lexically (meaning it does not bind it's own this).
Use normal function expressions instead:
module.exports = (options) => {
return {
a: function(a){
console.log(a);
},
b: function(b){
this.c('c');
console.log(b)
},
c: function(c){
console.log(c);
}
};
};
Browserfied example:
let f = (options) => {
return {
a: function(a){
console.log(a);
},
b: function(b){
this.c('c');
console.log(b)
},
c: function(c){
console.log(c);
}
};
};
f().a("a");
f().b("b");
f().c("c");
You can try and export a class, just pass options to your constructor
class InnerCall {
constructor(options) {
this.options = options;
}
a(a) {
console.log(a);
}
b(b) {
this.c('c');
console.log(b);
}
c(c) {
console.log(c);
}
}
const example = new InnerCall({ option: 'Im an option' });
example.b('check this out');
console.log(example.options.option);

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