Get selected message data in Thunderbird extension - javascript

I need to get some e-mail message data in my Thunderbird extension. I found this example on MDN (https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIMsgMessageService):
var content = "";
var MessageURI = GetFirstSelectedMessage();
var MsgService = messenger.messageServiceFromURI(MessageURI);
var MsgStream = Components.classes["#mozilla.org/network/sync-stream-listener;1"].createInstance();
var consumer = MsgStream.QueryInterface(Components.interfaces.nsIInputStream);
var ScriptInput = Components.classes["#mozilla.org/scriptableinputstream;1"].createInstance();
var ScriptInputStream = ScriptInput.QueryInterface(Components.interfaces.nsIScriptableInputStream);
ScriptInputStream.init(consumer);
try {
MsgService.streamMessage(MessageURI, MsgStream, msgWindow, null, false, null);
} catch (ex) {
alert("error: "+ex)
}
ScriptInputStream .available();
while (ScriptInputStream .available()) {
content = content + ScriptInputStream .read(512);
}
alert(content);
However, when I run it I get the following error:
Timestamp: 2013.06.21. 14:47:21
Error: ReferenceError: GetFirstSelectedMessage is not defined
Source File: chrome://edus_extension/content/messengerOverlay.js
Line: 90
What is this 'GetFirstSelectedMessage' function and how can I get message URI without using it?

This documentation looks fairly outdated. I would suggest:
using gFolderDisplay.selectedMessage (try typing top.opener.gFolderDisplay.selectedMessage in the Error Console),
reading some recent code that uses Services and MailServices so as to simplify your code.
That being said, I don't know what you're trying to achieve but:
you'd certainly be better off using a wrapper such as MsgHdrToMimeMessage (self-reference: http://blog.xulforum.org/index.php?post/2011/01/03/An-overview-of-Thunderbird-Conversations)
if you absolutely, absolutely need to get the raw contents of the message, http://mxr.mozilla.org/comm-central/source/mailnews/db/gloda/modules/mimemsg.js#223 has an example on how to do that (it's the implementation of the said MsgHdrToMimeMessage; by simplifying it, you should be able to get directly the raw data of the message).
Good luck with that, once you get a working sample, please add it to the MDN wiki!
Cheers,
jonathan

Related

Chrome extension reset overridden function

The problem:
A chrome extension I am working on needs a location spoofer. It works, however I cannot 'unset' it.
What I have so far:
Let's examine the relevant code. This is a part of a content script.
let cachedGeoLocFunc = navigator.geolocation.getCurrentPosition
let geoSpoofCode = conf => `
(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition = function(success) { return success(${conf}); }
} else {
console.error('Geolocation is not supported in this browser');
}
})()
`
browser.runtime
.sendMessage({ type: 'request-spoofed-coords' })
.then(curCoords => {
//json from state, contains current spoofed locale
if (curCoords) {
let script = document.createElement('script')
script.textContent = geoSpoofCode(curCoords)
document.documentElement.appendChild(script)
script.remove()
} else {
//revert to default behavior
let unSetScript = document.createElement('script')
unSetScript.textContent = `
(function() {
navigator.geolocation.getCurrentPosition = ${cachedGeoLocFunc};
})()`
document.documentElement.appendChild(unSetScript)
unSetScript.remove()
}
})
As you can see, I am overriding the chrome native function and providing my own value. This works fine for spoofing a location.
Unexpected behaviour:
Conceptually I imagined this would work. I am caching the native chrome function so I can later reset it (see the else). In practice I get this error when this content script gets injected into a page.
Uncaught SyntaxError: Unexpected identifier
And it breaks here (as per the chrome inspector)
Screen shot of error
My questions!
So, it just injects [ native code ] instead of the actual function (at-least that is what it looks like).
Does anyone know how I can un-override this function. Is there an elegant way to do this?
How does caching in chrome work, is there ever a way to view this native code
Anyways help would be appreciated. Hope you all have a great day!
Ok, this was a misunderstanding as #wOxxOm pointed out. Please refer to their response. Content scripts do not affect or truly 'override' api functions.

In Netsuite, ReferenceError nlapiCreateFile and nlapicreatecsvimport is not defined

In netsuite, I write the these code but I face a problem as
ReferenceError nlapiCreateFile is not defined
Code:
function creatingFile() {
var file = "xxxxx";
var fileObj = nlapiCreateFile('mycsv.csv','CSV',file); // Error !!!
nlapiSendEmail(15,'epost#xx.com,"subject" ,fileObj, null, null, null, null);
}
I have some similar old 1.0 code that works just fine. From a quick glance that is probably failing due to the "file" variable not being defined, and you have an extra apostrophe in the nlapiSendEmail function. Is that defined as a global variable earlier on in your script, also is "x" defined as an email address or internal ID?
Try running it with some try catch statements to get more specific error information. This should give you enough information for debugging where your problem is at.
function creatingFile(){
var fileContents='ASDFASDf,asdfgasfasdf';
var folderID='12345'; //replace with a valid folder internal ID.
try{
var fileObj=nlapiCreateFile('mycsv.csv','CSV',fileContents);
fileObj.setFolder(folderID);
var fID=nlapiSubmitFile(fileObj);
}catch(err01){
nlapiLogExecution('DEBUG','ERROR 01',JSON.stringify(err01));
}
try{
nlapiSendEmail(15,x,"asd",fID,null,null,null,null);
}catch(err02){
nlapiLogExecution('DEBUG','ERROR 02',JSON.stringify(err02));
}
}
I believe you are running into what I would consider a "bug", but NetSuite may disagree. If you are calling your creatingFile() function from a user event (i.e. a button on the Suitelet form, etc), that seems to fall under the category of "client script" in NetSuite logic, and the nlapiCreateFile function is not available in Client script context. This is not at all intuitive because, from my perspective, it's all part of the Suitelet, which is supported for that function. The only way I found to work around it is to create the file on load of the script, not on action of the user. However, this has resulted in other issues I haven't figured out yet, such as how I use the newly created file object in the client context once the customer clicks the button (I'm trying to send the file as an email attachment).

Infragistics ig.WebCapture Error

$('#btnTest').click(function () {
var captcha = $IG.WebCaptcha.find('capWebCaptcha');
alert(captcha.get_validationFailed());
// alert($IG.WebCaptcha);
});
This is throwing the following error:
Uncaught TypeError: $IG.WebCaptcha.find is not a function
I found the example from the URL below:
http://www.infragistics.com/help/aspnet/webcaptcha_captcha_validation.html
I am following all the instructions as provided. Has anybody seen this before or can somebody offer a work-around?
You can try to get reference using var captcha = ig_controls.capWebCaptcha, where the Id may differ if teh control is placed in panel, loaded from user control, etc.

Copy to clipboard with Javascript in Firefox

I really need a way to copy some text to the OS clipboard in Firefox.
Know it is easy in IE and not possible in Chrome and Opera unless flash is used. Because of different reasons I am unable to use the flash solution!
Had it working in the past but now the netscape.security.PrivilegeManager.enablePrivilege is protected as far as I can figure out (since ver. 17).
It looks as if it is still possible according to this article:
https://developer.mozilla.org/en-US/docs/Using_the_Clipboard
Believe it is still necessary to enable the possibility in the user.js file like this
user_pref("capability.policy.policynames", "allowclipboard");
user_pref("capability.policy.allowclipboard.sites", "http://");
user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess");
But how shall I do it? Have made some test without great success and think there is no guide on the web that explain how it shall be done in a generic way. E.g. a simple guide about how to enable javascript access to the clipboard. Hopefully also a guide that can be used by the novice user. Like to do it and post it here but need a working solution first.
According to the web there are 2 solutions for copy to clipboard;
document.execCommand("copy", false, null)
and
var gClipboardHelper = Components.classes["#mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
gClipboardHelper.copyString("Put me on the clipboard, please.");
Both generate a failure with my first try.
The solution below need the user to press CTRL+C and I need a solution where the text shall copy based on the press of a button (many on a single page).
https://stackoverflow.com/questions/4344325/copy-to-clipboard-on-firefox-and-google-chrome/11346026#11346026
My old solution was like this:
var clip = Components.classes['#mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if(clip)
{
var trans = Components.classes['#mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if(trans)
{
var str = new Object();
var len = new Object();
var str = Components.classes["#mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
if(str)
{
var clipid=Components.interfaces.nsIClipboard;
if(clipid)
{
str.data = cliptext;
trans.addDataFlavor('text/unicode');
trans.setTransferData("text/unicode", str, cliptext.length*2);
clip.setData(trans, null, clipid.kGlobalClipboard); // No return value
return 0;
}
}
}
}
Components.classes is undefined in unprivileged code (not add-on etc) so I do not believe any solution with this will work any more. One option is to make an add-on that will execute in privileged code area and send the text that shall be copied to this add-on for it to handle the copy to the OS clipboard (nice new possible project).
This only leave document.execCommand("copy", false, null) in the field as a stand alone solution.
Tried this code and it does not copy anything to the OS clipboard - but do not generate any errors btw.
var pre = document.getElementById('pcryptcopytext');
if(!pre)
{
pre = document.createElement("pre");
pre.setAttribute('id', 'pcryptcopytext');
pre.setAttribute('style', 'opacity: 0; position: absolute; top: -10000px; right: 0;');
document.body.appendChild(pre);
}
pre.innerHTML = cliptext;
pre.contentEditable = true;
//pre.unselectable = "off";
//pre.focus();
if (document.createRange)
{
var rng = document.createRange();
rng.selectNodeContents(pre);
document.execCommand("copy", false, null);
document.body.removeChild(pre);
}
So, anybody got a working solution?
Looks like this is not supported any more, and there is no replacement :(
https://support.mozilla.org/en-US/questions/977068#answer-500083
Maybe making some noise in a Firefox bug will help us get a (safe) solution.
Solved by creating a Firefox Add-on that exposes the clipboard object: https://github.com/myplaceonline/myplaceonline_ffclipboard
Example:
if (window.ffclipboard) {
window.ffclipboard.setText("clipboard text");
}
You can use firefox navigator object
navigator.clipboard.writeText("text you want to copy").then(() => {
// on success
}, (e) => {
// on error
});
document.execCommand("copy");

Improving our javascript error reporting

So right now we have some generic code to report errors either from our code or third party code. Our project is a JQM/Phonegap project for iOS. What is happening is we pretty much always get the same useless error... TypeError: 'undefined' is not a function... with no line number or other helpful information. Is there a way I could change the code to maybe get WHAT is undefined or WHERE it is?
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
//Handle errors not in a jquery event handler
//DebugMessage(errorMSg + " "+ url + " " + lineNumber);
var ex = new Error(errorMsg, url, lineNumber);
HandleError(ex, "window.onerror");
//HandleError sends the error object to
//a webservice to log the error.
return true;
};
Any tips on debugging javascript errors would help as well.
In recent months, browsers have extended the signature of window.onerror to provide more information.
window.onerror = function(msg, file, line, col, error) {
// backwards compat
if (!error) {
error = new Error(msg);
}
// send error to your logger
}
This should give you a lot more information. But there are still things where you need better context. You should check out some third-party tools for this like TrackJS that automatically give you this, plus extra information on how the error occurred.
Disclaimer: I am one of the original authors of TrackJS, so I know a bunch about JavaScript errors :)
Have you heard of Ripple? It is a mobile emulator for Chrome designed for testing PhoneGap applications.
That might help you find your errors before you debug on the devices.

Categories

Resources