Chrome Extensions synchronous calls - create window only after window closed - javascript

I have this code:
function voteNewWindow(mailNum) {
chrome.windows.create({
url: 'http://www.google.com',
incognito: true
}, function (window) {
console.log('created ' + window.id);
chrome.tabs.query({
active: true,
windowId: window.id
}, function (tabs) {
var tab = tabs[0];
chrome.tabs.executeScript(tab.id, {
file: "jquery-2.1.1.min.js"
}, function () {
chrome.tabs.executeScript(tab.id, {
file: "content_script.js"
}, function () {
chrome.tabs.sendMessage(tab.id, {
email: JSON.parse(localStorage.mailList)[mailNum]
}, function (response) {
console.log(response);
chrome.windows.remove(window.id);
console.log('window ' + window.id + " removed");
});
});
});
});
});
}
function execute() {
for (var i = 0; i < JSON.parse(localStorage.mailList).length; i++) {
voteNewWindow(i);
}
}
The problem is that all windows open at the same time. I want a window to open only when the one before is closed. I want voteNewWindow() to finish all it has to do before another voteNewWindow() executes.
Any help would be appreciated. Thanks

JavaScript Promises to the rescue!
function voteNewWindow(mailNum) {
return function(){
return new Promise( function (resolve, reject){
chrome.windows.create({
/* ... */
}, function (response) {
console.log(response);
chrome.windows.remove(response.id);
console.log('window ' + response.id + " removed");
resolve(); // Proceed to the next
});
/* ... */
}
}
}
function execute() {
var sequence = Promise.resolve();
for (var i = 0; i < JSON.parse(localStorage.mailList).length; i++) {
sequence = sequence.then(voteNewWindow(i));
}
}
See this section to understand what's happening here. Basically, we're creating a chain of Promises glued together by then, which ensures the next one will start executing only after the previous one has finished.
If you need to do any other action after execute(), put it at the end of the sequence:
function execute(callback) {
var sequence = Promise.resolve();
for (var i = 0; i < JSON.parse(localStorage.mailList).length; i++) {
sequence = sequence.then(voteNewWindow(i));
}
sequence.then(callback);
}

You can use then-chrome library, that wraps chrome api in promise calls.
And your nested callbacks can be modified to something like this
var thenChrome = require('then-chrome');
function voteNewWindow(mailNum) {
return thenChrome.windows.create({url: 'http://www.google.com', incognito: true})
.then(function(window) {
return thenChrome.tabs.query({active: true, windowId: window.id})
})
.then(function(tabs) {
return tabs[0];
})
.then(function(tab) {
return thenChrome.tabs.executeScript(tab.id, {file: 'jquery.js'});
})
...

Related

Chrome Extension: "No resource with given identifier found" when trying to Network.getResponseBody

I'm writing a Chrome Extension that can get HTTP response for a site. I try to use debugger for getting response body:
var gCurrentTab;
chrome.debugger.onEvent.addListener(function (source, method, params) {
if (gCurrentTab.id != source.tabId) {
return;
}
if (method == "Network.loadingFinished") {
var tabId = source.tabId;
var requestId = params.requestId;
chrome.debugger.sendCommand(
source,
"Network.getResponseBody",
{"requestId": requestId},
function (body) {
console.log(body);
chrome.debugger.detach(source);
});
}
}
);
chrome.webRequest.onBeforeRequest.addListener(function (details) {
var url = details.url;
if (url.indexOf('/mypage') >= 0) {
chrome.tabs.query({
currentWindow: true,
active: true
}, function (tabs) {
gCurrentTab = tabs[0];
chrome.debugger.attach({
tabId: gCurrentTab.id
}, "1.0", function () {
chrome.debugger.sendCommand({
tabId: gCurrentTab.id
}, "Network.enable");
});
});
}
},
{urls: []}, ["requestBody", "blocking"]);
But I always get
Unchecked runtime.lastError while running debugger.sendCommand: {"code":-32000,"message":"No resource with given identifier found"}
at chrome-extension://ikphgobkghdkjkfplgokmapjlbdfeegl/background.js:11:29
error, and the body is undefined.
Does anyone have idea about why this happen? Thanks!
It was because the website sends many responses, and this code will see another request other than I want, then detach the debugger so I can't get the result.
To solve this, just use a single debugger and do not detach it, or only detach when it's safe to.
var gAttached = false;
var gRequests = [];
var gObjects = [];
chrome.debugger.onEvent.addListener(function (source, method, params) {
if (method == "Network.requestWillBeSent") {
// If we see a url need to be handled, push it into index queue
var rUrl = params.request.url;
if (getTarget(rUrl) >= 0) {
gRequests.push(rUrl);
}
}
if (method == "Network.responseReceived") {
// We get its request id here, write it down to object queue
var eUrl = params.response.url;
var target = getTarget(eUrl);
if (target >= 0) {
gObjects.push({
requestId: params.requestId,
target: target,
url: eUrl
});
}
}
if (method == "Network.loadingFinished" && gObjects.length > 0) {
// Pop out the request object from both object queue and request queue
var requestId = params.requestId;
var object = null;
for (var o in gObjects) {
if (requestId == gObjects[o].requestId) {
object = gObjects.splice(o, 1)[0];
break;
}
}
// Usually loadingFinished will be immediately after responseReceived
if (object == null) {
console.log('Failed!!');
return;
}
gRequests.splice(gRequests.indexOf(object.url), 1);
chrome.debugger.sendCommand(
source,
"Network.getResponseBody",
{"requestId": requestId},
function (response) {
if (response) {
dispatch(source.tabId, object.target, JSON.parse(response.body));
} else {
console.log("Empty response for " + object.url);
}
// If we don't have any request waiting for response, re-attach debugger
// since without this step it will lead to memory leak.
if (gRequests.length == 0) {
chrome.debugger.detach({
tabId: source.tabId
}, function () {
chrome.debugger.attach({
tabId: source.tabId
}, "1.0", function () {
chrome.debugger.sendCommand({
tabId: source.tabId
}, "Network.enable");
});
});
}
});
}
}
);
var initialListener = function (details) {
if (gAttached) return; // Only need once at the very first request, so block all following requests
var tabId = details.tabId;
if (tabId > 0) {
gAttached = true;
chrome.debugger.attach({
tabId: tabId
}, "1.0", function () {
chrome.debugger.sendCommand({
tabId: tabId
}, "Network.enable");
});
// Remove self since the debugger is attached already
chrome.webRequest.onBeforeRequest.removeListener(initialListener);
}
};
// Attach debugger on startup
chrome.webRequest.onBeforeRequest.addListener(initialListener, {urls: ["<all_urls>"]}, ["blocking"]);
// Filter if the url is what we want
function getTarget(url) {
for (var i in TARGETS) {
var target = TARGETS[i];
if (url.match(target.url)) {
return i;
}
}
return -1;
}
const TARGETS = [
{url: '/path1', desc: 'target1'},
{url: '/path2', desc: 'target2'}
]
I am facing similar issue. I figured that sendCommand was not executing immediately. I was facing the issue for the requests which are sent before sending "Network.enable" was complete. Try adding completion for
chrome.debugger.sendCommand({
tabId: gCurrentTab.id
}, "Network.enable")

angular doesn't print data after scanning qr

I'm working with NativeStorage and barcodeScanner plugins for cordova.
The capture works well, and I receive the QRCode, but for any reason angular doesn't print it.
After working a lot on my code, I'm not able to do a valid callback, so angular can print it binding the data.
Here bellow I paste the code.
read.js
(function() {
'use strict';
var read = angular.module('app.read', ['monospaced.qrcode']);
read.controller('ReadController', [
function() {
var data = this;
var qr = function(string) {
data.code = string;
console.log(string);
};
cordova.plugins.barcodeScanner.scan(
function(result) {
if (!result.cancelled) {
if (result.format === "QR_CODE") {
(function(cb) {
cb(result.text);
})(qr);
NativeStorage.getItem("historic", function(d) {
var storage = JSON.parse(d);
storage.push(result.text);
NativeStorage.setItem("historic", JSON.stringify(storage), function(response) {}, function(e) {
console.log(e);
});
}, function(e) {
window.alert("Scanning failed: " + e);
});
}
}
},
function(e) {
window.alert("Scanning failed: " + e);
}, {
"preferFrontCamera": true, // iOS and Android
"showFlipCameraButton": true, // iOS and Android
"prompt": "Place a barcode inside the scan area", // supported on Android only
"formats": "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
"orientation": "portrait" // Android only (portrait|landscape), default unset so it rotates with the device
}
);
}
]);
}());
read.html
<div ng-controller="ReadController as myRead">
<qrcode version="5" error-correction-level="H" size="200" data="{{myRead.code}}" href="{{myRead.code}}"></qrcode>
{{myRead.code}}
</div>
Just adding some extra tests I have done before, I just missed the barcodeScanner.scan process and I did just the storage as I show bellow:
NativeStorage.getItem("historic", function (d) {
var storage = JSON.parse(d);
storage.push('https://google.es');
data.code = 'https://google.es';
NativeStorage.setItem("historic", JSON.stringify(storage), function (response) {}, function (e) {
console.log(e);
});
}, function (e) {
window.alert("Scanning failed: " + e);
});
Could you show me where am I wrong?
Thanks in advice.
A qualified guess is that the callbacks from cordova.plugins.barcodeScanner.scan doesn't trigger AngularJS' digest cycle, which means no dirty checking will be performed, no changes will be detected and the UI won't be updated.
Try wrapping the code in the success callback in $apply:
function(result) {
$scope.$apply(function() {
if (!result.cancelled) {
if (result.format === "QR_CODE") {
(function(cb) {
cb(result.text);
})(qr);
NativeStorage.getItem("historic", function(d) {
var storage = JSON.parse(d);
storage.push(result.text);
NativeStorage.setItem("historic", JSON.stringify(storage), function(response) {}, function(e) {
console.log(e);
});
}, function(e) {
window.alert("Scanning failed: " + e);
});
}
}
});
}

Delete items synchronously angularjs

I have to delete items in a for loop the moment I close a bootstrap modal.
Currently I am setting a delay of 3 secs on the modal close, so that the delete can happen within those 3secs in the background but this is not very efficient.
What is the best way to ensure that the modal closes only when all the items are deleted successfully? Perhaps by making the delete synchronous ? Or promises?
$scope.idList = [1, 2, 3];
$scope.deleteItems = function(deleteList){
angular.forEach( deleteList, function(item) {
DeleteAPI.remove({itemId: item}, {}, $scope.delSuccess, $scope.delError);
});
}
$scope.close = function(){
var pmodal = $modal.open( {
templateUrl: 'route/pmodal.html',
controller: 'DeleteCtrl'
} );
pmodal.result.then(
function(check) {},
function(check) {
if ( check=='proceed' ) {
$scope.deleteItems( $scope.idList );
$timeout( function() {
$modalInstance.dismiss('cancel');
}, 3000);
}
},
function(check) {}
);
}
You can use $q.all or you can simple count responses as Javascript is not multithread:
pmodal.result.then(
var success = 0;
var failed = 0;
var check = function() {
if (success + failed == deleteList.length) {
if (failed != 0) {
// do smth?
} else {
$modalInstance.dismiss('cancel');
}
}
}
angular.forEach( deleteList, function(item) {
DeleteAPI.remove({itemId: item}, {}, function() {
success++;
check();
}, function() {
failed++;
check();
});
});

ExtJs minify Gets ignored

We have a CMS so I don't have access to the header of the HTML page which gets rendered for our extjs implementation. So I had to make a workaround which is like this:
Ext.local = {};
var lang = {
initLang: function (revisionNr) {
var local = localStorage.getItem('localLang')
if (!local) {
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
this.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
}
}
},
loadLangRemote: function (data) {
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
lang.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
},
loadLangLocal: function (data) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = 'js/freetext-deploy.min.js?rev={/literal}{$revisionNr}{literal}';
document.getElementsByTagName('head')[0].appendChild(jsElm);
Ext.Date.defaultFormat = 'd-m-Y';
if (!debug) {
Ext.Loader.config.disableCaching = true;
}
Ext.application({
name: 'freetextOrder',
appFolder: 'modules/extjs/freetextOrder/app',
controllers: [
'Main'
],
launch: function () {
var freetextOrder = Ext.create('Ext.container.Container', {
renderTo: Ext.get('freetextOrderDiv'),
layout: 'fit',
id: 'catalogAdministrationDiv_ext',
height: 800,
cls: 'x-dig-override',
items: [Ext.create('freetextOrder.view.base.MainView', {})],
layout:'fit'
});
}
});
Ext.local = data;
}
};
lang.initLang();
The problem I'm having is that the minified version gets ignored completely. I see it load on the http request but extjs ignores them.... even though I can see the objects are being created after include (via console log)
Anyone any idea how I can achieve this?
as i see none found the answer so i post my own here wich i came up with.
Since i could for the love of god not load the damn thing i refactored the loader and exported it into a Js. file. wich i reqired and called later on in code.
exported lang.js file:
Ext.define('Lang', {
singleton: true,
ApplicationConf: null,
Launch: function (launchConfig) {
this.ApplicationConf = launchConfig;
var local = localStorage.getItem('localLang');
var me = this;
this.loadLangRemote = function (data) {
debugger;
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
me.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
};
this.loadLangLocal = function (data) {
Ext.local = data;
Ext.lang = function (langId) {
if (Ext.local[langId]) {
return Ext.local[langId];
}
delete window.localStorage.localLang;
localStorage.setItem('localLangBackup', true);
return langId;
}
Ext.application(me.ApplicationConf);
};
if (!local) {
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
debugger;
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
debugger;
me.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
}
}
},
})
And IMPORTANT was to add the
Ext.onReady(function () {
Lang.Launch({
name: 'catalogAdministration',
appFold....
To the call of the Launch function in code, bacause it would have been not defined at run time. i added the file to the minified file first and call the Lang.Launch instead Ext.Application.
Hope somone has use of my solution :)

Jquery Context Menu ajax fetch menu items

I have a jquery context menu on my landing page where I have hardcode menu items. Now I want to get the menu items from server. Basically the idea is to show file names in a specified directory in the context menu list and open that file when user clicks it...
This is so far I have reached..
***UPDATE***
C# code
[HttpPost]
public JsonResult GetHelpFiles()
{
List<Manuals> manuals = null;
var filesPath = Server.MapPath(#"\HelpManuals");
var standardPath = new DirectoryInfo(filesPath);
if (standardPath.GetFiles().Any())
{
manuals = standardPath.GetFiles().Select(x => new Manuals
{
Name = GetFileNamewithoutExtension(x.Name),
Path = x.Name
}).ToList();
}
return Json(manuals, JsonRequestBehavior.AllowGet);
}
private string GetFileNamewithoutExtension(string filename)
{
var extension = Path.GetExtension(filename);
return filename.Substring(0, filename.Length - extension.Length);
}
JavaScript Code
$.post("/Home/GetHelpFiles", function (data) {
$.contextMenu({
selector: '#helpIcon',
trigger: 'hover',
delay: 300,
build: function($trigger, e) {
var options = {
callback: function(key) {
window.open("/HelpManuals/" + key);
},
items: {}
};
$.each(data, function (item, index) {
console.log("display name:" + index.Name);
console.log("File Path:" + index.Path);
options.items[item.Value] = {
name: index.Name,
key: index.Path
}
});
}
});
});
Thanks to Matt. Now, the build function gets fire on hover.. but im getting illegal invocation... and when iterating through json result, index.Name and this.Name gives correct result. But item.Name doesn't give anything..
to add items to the context menu dynamically you need to make a couple changes
$.contextMenu({
selector: '#helpIcon',
trigger: 'hover',
delay: 300,
build: function($trigger, e){
var options = {
callback: function (key) {
var manual;
if (key == "adminComp") {
manual = "AdminCompanion.pdf";
} else {
manual = "TeacherCompanion.pdf";
}
window.open("/HelpManuals/" + manual);
},
items: {}
}
//how to populate from model
#foreach(var temp in Model.FileList){
<text>
options.items[temp.Value] = {
name: temp.Name,
icon: 'open'
}
</text>
}
//should be able to do an ajax call here but I believe this will be called
//every time the context is triggered which may cause performance issues
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'get',
cache: false,
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (_result) {
if (_result.Success) {
$.each(_result, function(item, index){
options.items[item.Value] = {
name: item.Name,
icon: 'open'
}
});
}
});
return options;
}
});
so you use build and inside of that define options and put your callback in there. The items defined in there is empty and is populated in the build dynamically. We build our list off of what is passed through the model but I believe you can put the ajax call in the build like I have shown above. Hopefully this will get you on the right track at least.
I solved this problem the following way.
On a user-triggered right-click I return false in the build-function. This will prevent the context-menu from opening. Instead of opeing the context-menu I start an ajax-call to the server to get the contextMenu-entries.
When the ajax-call finishes successfully I create the items and save the items on the $trigger in a data-property.
After saving the menuItems in the data-property I open the context-menu manually.
When the build-function is executed again, I get the items from the data-property.
$.contextMenu({
build: function ($trigger, e)
{
// check if the menu-items have been saved in the previous call
if ($trigger.data("contextMenuItems") != null)
{
// get options from $trigger
var options = $trigger.data("contextMenuItems");
// clear $trigger.data("contextMenuItems"),
// so that menuitems are gotten next time user does a rightclick
// from the server again.
$trigger.data("contextMenuItems", null);
return options;
}
else
{
var options = {
callback: function (key)
{
alert(key);
},
items: {}
};
$.ajax({
url: "GetMenuItemsFromServer",
success: function (response, status, xhr)
{
// for each menu-item returned from the server
for (var i = 0; i < response.length; i++)
{
var ri = response[i];
// save the menu-item from the server in the options.items object
options.items[ri.id] = ri;
}
// save the options on the table-row;
$trigger.data("contextMenuItems", options);
// open the context-menu (reopen)
$trigger.contextMenu();
},
error: function (response, status, xhr)
{
if (xhr instanceof Error)
{
alert(xhr);
}
else
{
alert($($.parseHTML(response.responseText)).find("h2").text());
}
}
});
// This return false here is important
return false;
}
});
I have finally found a better solution after reading jquery context menu documentation, thoroughly..
C# CODE
public JsonResult GetHelpFiles()
{
List<Manuals> manuals = null;
var filesPath = Server.MapPath(#"\HelpManuals");
var standardPath = new DirectoryInfo(filesPath);
if (standardPath.GetFiles().Any())
{
manuals = standardPath.GetFiles().Select(x => new Manuals
{
Name = GetFileNamewithoutExtension(x.Name),
Path = x.Name
}).ToList();
}
return Json(manuals, JsonRequestBehavior.AllowGet);
}
HTML 5
<div id="dynamicMenu">
<menu id="html5menu" type="context" style="display: none"></menu>
</div>
JavaScript Code
$.post("/Home/GetHelpFiles", function (data) {
$.each(data, function (index, item) {
var e = '<command label="' + item.Name + '" id ="' + item.Path + '"></command>';
$("#html5menu").append(e);
});
$.contextMenu({
selector: '#helpIcon',
trigger: 'hover',
delay: 300,
items: $.contextMenu.fromMenu($('#html5menu'))
});
});
$("#dynamicMenu").on("click", "menu command", function () {
var link = $(this).attr('id');
window.open("/HelpManuals/" + link);
});
Here's my solution using deferred, important to know that this feature is supported for sub-menus only
$(function () {
$.contextMenu({
selector: '.SomeClass',
build: function ($trigger, e) {
var options = {
callback: function (key, options) {
// some call back
},
items: JSON.parse($trigger.attr('data-storage')) //this is initial static menu from HTML attribute you can use any static menu here
};
options.items['Reservations'] = {
name: $trigger.attr('data-reservations'),
icon: "checkmark",
items: loadItems($trigger) // this is AJAX loaded submenu
};
return options;
}
});
});
// Now this function loads submenu items in my case server responds with 'Reservations' object
var loadItems = function ($trigger) {
var dfd = jQuery.Deferred();
$.ajax({
type: "post",
url: "/ajax.php",
cache: false,
data: {
// request parameters are not importaint here use whatever you need to get data from your server
},
success: function (data) {
dfd.resolve(data.Reservations);
}
});
return dfd.promise();
};

Categories

Resources