chrome extension connection issues - google-chrome-extension

I have written an extension for google chrome and I have a bug I need a help solving.
what I do is using either a text selection or an input of text search for photos on flickr and then create a results tab.
The extension works most of the times. but sometimes it creates a blank tab with no results and when I repeat the same search it then shows results. I figured that it's something to do with the html files messaging maybe something to do with them communicating. I have to say that I always receive the results from flickr so that the request/responce with flickr works ok. Sometimes the error happens when I play with other tabs or do something on other tabs while waiting for results. can you please help me figure out where's the fault?
the background file:
function searchSelection(info,tab){
var updated;
if(info.selectionText==null){
var value = prompt("Search Flickr", "Type in the value to search");
updated=makeNewString(value);
}
else{
updated=makeNewString(info.selectionText);
}
var resultHtml;
var xhReq = new XMLHttpRequest();
xhReq.open(
"GET",
"http://api.flickr.com/services/rest/?method=flickr.photos.search&text="+updated+
"&api_key=a0a60c4e0ed00af8d70800b0987cae70&content_type=7&sort=relevance&per_page=500",
true);
xhReq.onreadystatechange = function () {
if (xhReq.readyState == 4) {
if (xhReq.status == 200) {
chrome.tabs.executeScript(tab.id, {code:"document.body.style.cursor='auto';"});
var photos = xhReq.responseXML.getElementsByTagName("photo");
if(photos.length==0){
alert("No results found for this selection");
chrome.tabs.executeScript(tab.id, {code:"document.body.style.cursor='auto';"});
return;
}
var myJSPhotos=[];
for(var i=0; i<photos.length; i++){
var data={"id":photos[i].getAttribute("id"),"owner":photos[i].getAttribute("owner"),
"secret":photos[i].getAttribute("secret"),"server":photos[i].getAttribute("server"),
"farm":photos[i].getAttribute("farm"),"title":photos[i].getAttribute("title")};
myJSPhotos[i]=data;
}
chrome.tabs.create({"url":"results.html"},function(thistab){
var port= chrome.tabs.connect(thistab.id);
port.postMessage({photos:myJSPhotos});
});
}
};
};
xhReq.send(null);
chrome.tabs.executeScript(tab.id, {code:"document.body.style.cursor='wait';"});
}
var context="selection";
var id = chrome.contextMenus.create({"title": "search Flickr", "contexts":[context,'page'],"onclick":searchSelection});
results html: has only a reference to the js file res.js
res.js :
chrome.extension.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
//*****//
var photos=msg.photos;
createPage(photos);
});
});
I have to mention that when the tab is empty if I put alert on the //*****// part it won't
fire.
but when I print out the photos.length at the tab create call back function part it prints out the correct result.

Try to set "run_at":"document_start" option for your res.js in the manifest.
I think callback from chrome.tabs.create is fired right away without waiting for page scripts to be loaded, so you might try something like this instead:
//global vars
var createdTabId = null;
var myJSPhotos = null;
xhReq.onreadystatechange = function () {
//assign myJSPhotos to a global var
chrome.tabs.create({"url":"results.html"},function(thistab){
createdTabId = thistab.id;
});
}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "complete" && tab.id == createdTabId) {
createdTabId = null;
//now page is loaded and content scripts injected
var port = chrome.tabs.connect(tab.id);
port.postMessage({photos:myJSPhotos});
}
});

Related

Userscript works in Tampermonkey on Chrome and Firefox, but doesn't work in Greasemonkey on Firefox

This script works just fine in Tampermonkey on both Chrome and Firefox, but doesn't work in Greasemonkey on Firefox. When I say it doesn't work I mean the button does not show up on the page. I'm using Chrome 61.0.3163.79 and Firefox 52.3.0.
The firefox console shows this warning but I'm not sure if it's relevant:
unreachable code after return statement[Learn More] jquery-1.3.2.min.js
Here's the code. Using greasemonkey on Firefox, I see "create button" in the console, but not "button has been created", which makes me think something is going wrong with the button creation. Any help greatly appreciated!
// ==UserScript==
// #name MyScript
// #namespace MyNS
// #description Adds a button to insert text into 2 text boxes
// #version 0.1
// #include *Removed for confidentiality*
// #compatible Greasemonkey
// ==/UserScript==
var descriptionText = "myDescription";
var testingText = "myTesting";
// Check if jQuery's loaded
function GM_wait() {
if (typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }
else { $ = unsafeWindow.jQuery; init(); }
}
// All your GM code must be inside this function
function init() {
var description = $('#description');
var testingDone = $('#testing_done');
function insertText(template, editor) {
if (template) {
if (!editor._editing) {
editor.startEdit();
}
editor._field.queue(function() {
var oldVal = editor._field.val();
editor._field.val(template + (oldVal ? "\n" : "") + oldVal);
editor._field.keyup();
editor._field.dequeue();
});
}
}
function createButton(editor) {
console.log("create button:");
editor._insertTextButton = $('<input/>')
.attr('type', 'button')
.attr('value', 'Insert CR Template')
.css('margin-left', '1em')
.click(function() {
insertText(testingText, testingDoneEditor);
insertText(descriptionText, descriptionEditor);
});
console.log("button has been created");
editor._insertTextButton.insertAfter(editor._editIcon);
}
descriptionEditor = description.data('inlineEditor');
testingDoneEditor = testingDone.data('inlineEditor');
createButton(descriptionEditor);
}
GM_wait();

Extjs and Spring success handler

I'm building web application with ExtJs and Spring. With ExtJs I'm uploading excel file and with spring I parse it. Everything works fine, although my success handler in ExtJs code doesn't work. I read many examples about that, but I still can't solve this problem. I hope you guys will help me.
This is ExtJs upload file function:
uploadFile: function(value, fld){
var me = this;
var id = this.getTipasCombobox().getValue();
var record = this.getTipasCombobox().getStore().getById(id);
var timeId = this.getLaikotarpiaiCombo().getValue();
var timeRecord = this.getLaikotarpiaiCombo().getStore().getById(timeId);
var fp = this.getUploadBtn().up('form').getForm();
if(fp.isValid()){
fp.submit({
url: Turtas.Properties.getServicePath()+'/save/' + record.data.resource,
waitMsg: 'Failas yra įkeliamas, prašome palaukti...',
success: function(){
console.log("Upload completed");
me.storeSelection(record.data.resource, timeRecord.data.open, timeRecord.data.year, true, me.restrictedPage())
}
})
}
},
And this is my controller function which I use to parse Excel:
#RequestMapping(value="turtas/save/gelezinkeliai", method=RequestMethod.POST)
public String saveGelezinkeliaiFromExcel(HttpServletResponse response, #RequestParam("file") MultipartFile file){
if (file.getSize() != 0){
ReadExcelFileToList excelFile = new ReadExcelFileToList();
List<Gelezinkeliai> gelezinkeliai = new ArrayList<Gelezinkeliai>();
gelezinkeliai = excelFile.readExcelData(/*fileName*/ file);
gelezinkeliai.remove(0);
Laikotarpis laikotarpis = new Laikotarpis();
laikotarpis = laikotarpiaiService.findById(2014);
for (GelezinkeliaiRest delGelezinkelis : service.getItems(2014, true, false)){
service.delete(delGelezinkelis);
}
List<Gelezinkeliai> finalGelezinkeliai = new ArrayList<Gelezinkeliai>();
for (Gelezinkeliai gelezinkelis : gelezinkeliai){
gelezinkelis.setLaikotarpis(laikotarpis);
finalGelezinkeliai.add(gelezinkelis);
GelezinkeliaiRest gelezinkeliaiRest = new GelezinkeliaiRest();
gelezinkeliaiRest.fromGelezinkeliai(gelezinkelis);
service.save(gelezinkeliaiRest, false);
}
response.setContentType("text/html");
return "{\"success\":true}";
}
else {
return "{\"success\":false}";
}
}
Response content-type is text/html and response is:
{"success":true}
If I manually reload page or store, data is updated, so functions work properly, but i want to catch event when the request ends, to reload store automatically. I have no idea what's wrong. Thanks for responses in advance!

SP.Ribbon.WebPartComponent.getWebPartAdder() returns undefined

I am using the source at http://blog.symprogress.com/2010/11/ribbon-insert-any-web-part-using-javascript/ to handle user web part button click event.
The function 'addWebPart()' calls a function 'SP.Ribbon.WebPartComponent.getWebPartAdder()' which is supposed to return adder instance but sometimes it returns undefined.
If I add a while loop to wait for the instance value to return correctly, the browser in my VM stalls for some time. When an instance is returned, the browser becomes responsive again. This only happens in some instances.
I am using SharePoint 2013 and the section of code I am referring to is:
addWebPart = function (wpCategory, wpTitle) {
var webPartAdder = SP.Ribbon.WebPartComponent.getWebPartAdder();
while (webPartAdder == undefined)
webPartAdder = SP.Ribbon.WebPartComponent.getWebPartAdder();
// ... Other stuff ...
}
How can this issue be resolved?
For anyone looking for an answer to this question, turns out you have to call 'LoadWPAdderOnDemand()' function then wait for the event '_spEventWebPartAdderReady'. Then query for 'window.WPAdder':
addWebPartDelayed = function (webPartAdder, wpCategory, wpTitle) {
var webPart = findWebPart(webPartAdder, wpCategory, wpTitle);
if (webPart) {
var zone = WPAdder._zones[0];
var wpid = WPAdder._createWebpartPlaceholderInRte();
WPAdder.addItemToPageByItemIdAndZoneId(webPart.id, zone.id, 0, wpid);
}
else
alert('ERROR: Web part not found! Please try again after sometime.');
},
addWebPart = function (wpCategory, wpTitle) {
var webPartAdder = window.WPAdder;
if (webPartAdder == undefined) {
LoadWPAdderOnDemand();
ExecuteOrDelayUntilEventNotified(
function () {
var webPartAdder = window.WPAdder;
addWebPartDelayed(webPartAdder, wpCategory, wpTitle);
},
"_spEventWebPartAdderReady");
}
else
addWebPartDelayed(webPartAdder, wpCategory, wpTitle);
};

How to get rid of the asynchoronous code here

I have been trying to retrieve the data using the MongoJS driver for node.js.The Code which I am using is as follows
req.on('end', function(){
var decodedBody = querystring.parse(fullBody);
story=decodedBody.name;
var z=new Array();
console.log(story);
res.writeHead(200,{'Content-Type': 'text/html'});
res.write('<html><body>');
db.frames.find({str_id:story}).toArray(function(err,doc){
console.log(doc);
for(var t=0;t<doc.length;t++)
{
var picid=doc[t].pic_id;
console.log(picid);
db.pictures.find({_id:picid}).toArray(function(err,pic){
res.write('<img src="'+pic[0].name+'"/>');
});
}
})
res.end('</body></html>');
});
The problem here is that because of the asynchronous nature of the code the response gets ends first and then the code inside the block of database gets executed and because of that nothing gets displayed on the browser i.e an image in this case .Thankx in advance.
Don't fight the asynchronous nature of node.js, embrace it!
So you should fire off all your requests, marking each one as completed when the response arrives. When all requests are completed, render your images and body/html closing tags.
I don't usually work with node.js, so I can make some mistakes, but it may look like this:
res.write('<html><body>');
db.frames.find({str_id:story}).toArray(function(err,doc){
console.log(doc);
var completed = {};
for(var t = 0; t < doc.length; t++) {
var picid = doc[t].pic_id;
completed.picid = false;
console.log(picid);
db.pictures.find({_id: picid}).toArray(function(err, pic) {
// mark request as completed
completed.picid = pic;
// check if all requests completed
var all_finished = true;
for(var k in completed) {
if(completed[k] === false) {
all_finished = false;
break;
}
}
// render final markup
if(all_finished) {
for(var k in completed) {
var pic = completed[k];
res.write('<img src="'+pic[0].name+'"/>');
}
res.end('</body></html>);
}
});
}
})
just put the res.end('</body></html>'); inside your db.frames.find function. Check when you reached doc.length - 1 and then send the end command.

CKEditor: Using dialogDefinition.onShow() throws C.preview not defined

Modifying CKEditor 3.6.2 is not easy, but I tried hard. One problem that is still open is the following:
In config.js we have:
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if(dialogName == 'image') {
dialogDefinition.onShow = function () {
var dialog = CKEDITOR.dialog.getCurrent();
var elem = dialog.getContentElement('info','htmlPreview');
elem.getElement().hide();
// and more stuff to do...
};
}
});
After the editor is loaded, and the user has uploaded an image, the following javascript error is thrown:
Error: C.preview is undefined
Source File: wysiwyg-editor/plugins/image/dialogs/image.js?t=B8DJ5M3
Line: 8
dialogDefinition.onShow seems to cause this error, as removing all elements from the code, and only calling onShow brings up the error. Using onLoad does work!
Using onShow on other dialogs is working fine, only the image dialog is not working as it should.
Btw, I asked in the CKEditor forum but nobody answered.
Stumbled across this when I was looking for a resolution. Figured I'd post what I ultimately did to solve it, albeit not 100% ideal.
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var tab, field, name = ev.data.name,
definition = ev.data.definition;
if( name == 'image' )
{
tab = definition.getContents( 'info' );
field = tab.get( 'htmlPreview' );
field.style = 'display: none';
}
});
This makes the preview window available for processing, just hides it from the dialog window.
Use CKEDITOR.tools.setTimeout() like this:
CKEDITOR.on('dialogDefinition', function(ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var dialog = dialogDefinition.dialog;
if (dialogName == 'image2') {
dialogDefinition.onShow = CKEDITOR.tools.override(dialogDefinition.onShow, function(original) {
return function() {
original.call(this);
CKEDITOR.tools.setTimeout( function() {
if (dialog.getContentElement('info', 'src').getValue() == '') {
dialog.selectPage('Upload');
}
}, 0);
}
});
}
});

Resources