OR operator in extendscript - javascript

I'm creating some scripts voor InDesign to speed up the process.
I have created a script where a certain line, I think, should work but InDesign disagrees.
It fails on ("Geen"||"None"); in the following
app.changeGrepPreferences.appliedCharacterStyle = myDoc.characterStyles.item("[Geen]"||"[None]");
I expect it to change to a characterStyle [Geen] or [None]. Depending on what is available in the predefined character styles.
What am I doing wrong? This seems kinda basic.

Unfortunately is not that easy. If you use doc.characterStyles.item('foo') it still will give you an [object CharacterStyle]. Even tough it does not exsist.
var doc = app.activeDocument;
$.writeln(doc.characterStyles.item('foo'));
// writes [object CharacterStyle] into the console
What you can do is use a try{}catch(error){} block and ask for the name property of that object. In that case InDesign will throw an error that you can catch. Then you can fall back to the default character style [None]
var doc = app.activeDocument;
try{
$.writeln(doc.characterStyles.item('foo').name);
}catch(e) {
$.writeln(e);
$.writeln(doc.characterStyles.item('[None]').name);
}
Edit: As mentioned by mdomino. You can use the isValid property.
var doc = app.activeDocument;
if(doc.characterStyles.item('foo').isValid === true) {
$.writeln('doc.characterStyles.item(\'foo\') exists');
} else {
$.writeln('use doc.characterStyles.item(\'[None]\') because ');
var defaultStyle = doc.characterStyles.item('[None]');
$.writeln(defaultStyle.name + ' is ' + defaultStyle.isValid);
}

Related

TypeError: Error #1009: Cannot access a property or method of a null object reference. at Slide1_fla::MainTimeline/frame1() AS3

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Slide1_fla::MainTimeline/frame1()
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Slide2_fla::MainTimeline/frame1()
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Side3_fla::MainTimeline/frame1()
I have tried all of the sources and still couldn't find any answer to fix this problem.
I am running Adobe Flash CS6 AS3
Whenever I run the script, I get this output and the file doesn't run properly. In the published file, the swf file isn't show completely, meaning the external .swf files are not fitted in the contentContainer.
My code is this:
var _swfLoader:Loader;
var _swfRequest:URLRequest;
var _swfPathArr:Array = new Array("Slide1.swf", "Slide2.swf", "Slide3.swf");
var _swfClipsArr:Array = new Array();
var _swfTempClip:MovieClip;
var _loadedSWFs:int;
var contact_btn:SimpleButton;
var news_btn:SimpleButton;
var portfolio_btn:SimpleButton;
startLoading(_swfPathArr);
function startLoading(pathArr:Array):void {
_swfLoader = new Loader();
_swfRequest = new URLRequest();
loadSWF(pathArr[0]);
}
function loadSWF(path:String):void {
setupListeners(_swfLoader.contentLoaderInfo);
_swfRequest.url = path;
_swfLoader.load(_swfRequest);
}
function setupListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, onSwfComplete);
dispatcher.addEventListener(ProgressEvent.PROGRESS, currentSwfProgress);
}
function currentSwfProgress(event:ProgressEvent):void {
var _perc:int = (event.bytesLoaded / event.bytesTotal) * 5;
// swfPreloader.percentTF.text = _perc + "10%";
}
function onSwfComplete(event:Event):void {
event.target.removeEventListener(Event.COMPLETE, onSwfComplete);
event.target.removeEventListener(ProgressEvent.PROGRESS, currentSwfProgress);
_swfTempClip = event.target.content;
_swfTempClip.customID = _loadedSWFs;
_swfClipsArr.push(_swfTempClip);
if(_loadedSWFs <_swfPathArr.length - 1) {
_loadedSWFs++;
loadSWF(_swfPathArr[_loadedSWFs]);
} else {
_swfLoader.unloadAndStop();
_swfLoader = null;
onCompletePreloading();
}
}
function onCompletePreloading():void {
contentContainer.addChild(_swfClipsArr[0]);
news_btn.enabled = true;
contact_btn.enabled = true;
portfolio_btn.enabled = true;
news_btn.addEventListener(MouseEvent.CLICK, setContent);
portfolio_btn.addEventListener(MouseEvent.CLICK, setContent);
contact_btn.addEventListener(MouseEvent.CLICK, setContent);
}
function setContent(event:MouseEvent):void {
var _swfToAdd:MovieClip;
switch(event.target.name) {
case "news_btn":
_swfToAdd = _swfClipsArr[0];
break;
case "portfolio_btn":
_swfToAdd = _swfClipsArr[1];
break;
case "contact_btn":
_swfToAdd = _swfClipsArr[2];
break;
}
contentContainer.removeChildAt(contentContainer.numChildren-1);
contentContainer.addChild(_swfToAdd);
trace(_swfToAdd.customID);
}
I used to face this problem when the loaded SWF contain "TLF Text".
So the fix? Make "ALL" your textfield in the loaded SWF "Classic Text" and hopefully your problem would be solved.
PS. An easy way to clean all TLF text from a FLA file is to change document script from ActionScript 3.0 to 2.0. Since TLF Text is only support in 3.0, they will immediately change back to Classic Text, and then change your script back to 3.0 again. :)

.gBrowser is undefined

I'm writing a restartless Firefoxextension where I have to enumerate all open tabs and work with them.
Here's the code-part that throws the error:
getInfoString : function ()
{
infos = "";
HELPER.alerting("url", "URL-Function");
var winMediator = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
HELPER.alerting("url", "Mediator initialized");
var mrw = winMediator.getEnumerator(null);
while(mrw.hasMoreElements())
{
var win = mrw.getNext();
var t = win.gBrowser.browsers.length;
HELPER.alerting("url", "browsers: " + t);
for (var i = 0; i < t; i++)
{
var b = win.gBrowser.getBrowserAtIndex(i);
if(b.currentURI.spec.substr(0,3) != "http")
{
continue;
}
HELPER.alerting(b.title,b.currentURI.spec);
var doc = b.contentDocument;
var src = doc.documentElement.innerHTML;
infos = infos + src
HELPER.alerting("doc", src);
}
}
return infos;
}
I have a JavascriptDebugger-Addon running while testing this and Firefox executes everything fine to the line
HELPER.alerting("url", "browsers: " + t);
But AFTER this line, the debugger-addons throws an error, saying that:
win.gBrowser is undefined
... pointing to the line:
var t = win.gBrowser.browsers.length;
But before it throws the error I get my alertmessage which gives me the correct number of tabs. So the error is thrown after the line was executed and not directly WHEN it was executed.
Does anyone has an idea how to fix this, because the extension stops working after the error has been thrown.
Greetz
P.S.: If someone has a better headline for this, feel free to edit it.
Using winMediator.getEnumerator(null) would give you all types of window, that may or may not be browser windows. You should try changing the following line
var mrw = winMediator.getEnumerator(null);
with
var mrw = winMediator.getEnumerator('navigator:browser');
I finally figured out that this behavior can happen sometimes.
I just rearranged the code a bit, removing some alerts inside the for-loop and it works just fine again.
So if someone has this error too, just rearrange your code and it should work like a charm again.

Object doesn't support this property or method in JavaScript

Okay, so I think I'm derping here again.. I'm using this code in a HTA (for a intranet application) instead of using just a normal HTML page.. when I "submit" my code I get the error message "Object doesn't support this property or method on line: 24 (which is where I close my file (via activexobjects)
HTML page uses:
<input name="Button1" type="button" value="Submit" onclick="getFormContent()" />
My Javascript file (external .js page) :
// Global Variables First!
var AllFormContent
var ManagerValue
function managerValueTrue(ManagerValue) {
ManagerValue = "Yes"
}
function managerValueFalse(ManagerValue) {
ManagerValue = "No"
}
function getFormContent(ManagerValue) {
var Mudkips = document.getElementById('ManagerName');
var ManagerName = Mudkips.options[Mudkips.selectedIndex].text;
var RandomText = document.getElementById('RandomText').value;
var Comment = document.getElementById('Comments').value;
AllFormContent = ManagerName + ", " + ManagerValue + ", " + RandomText + ", " + Comments
writeMyFile();
}
function writeMyFile(AllFormContent) {
var filesys = new ActiveXObject("Scripting.FileSystemObject");
var filetxt = filesys.OpenTextFile("C:\\MyFile.csv", 8) ;
filetxt.WriteLine(AllFormContent);
filetxt.Close;
}
"line 24" refers to "filetext.close" though I imagine it might have to do with "AllFormContent" or a previous line? I've tested the code, I know I get to the writeMyFile function, I know the ActiveXObject works fine.. Any ideas on what I'm derping with here?
Thanks :]
As everyone suggested in the comments but didn't answer, just add parantheses to Close at writeMyFile().
function writeMyFile(AllFormContent) {
var filesys = new ActiveXObject("Scripting.FileSystemObject");
var filetxt = filesys.OpenTextFile("C:\\MyFile.csv", 8) ;
filetxt.WriteLine(AllFormContent);
filetxt.Close();
}
Close is a method of the Scripting.FileSystemObject in JavaScript while it's more like a subprocedure for VBScript. To call functions and methods in JavaScript, you have to close the reference with parantheses while in VBScript it is unnecessary to call a Sub with parantheses and with multiple params it even gives an error (I think?).
There is not alot of documentation for JScript and the ActiveXObjects for WScript, most of it is covered in VBScript so there is often confusion in this aspect.

Appending to External Browser Window

I have a Windows app that contains a browser control that loads pages from my website. However, due to the Windows app, I cannot debug Javascript in the usual ways (Firebug, console, alerts, etc).
I was hoping to write a jQuery plug-in to log to an external browser window such that I can simply do something like:
$.log('test');
So far, with the following, I am able to create the window and display the templateContent, but cannot write messages to it:
var consoleWindow;
function getConsoleWindow() {
if (typeof (consoleWindow) === 'undefined') {
consoleWindow = createConsoleWindow();
}
return consoleWindow;
}
function createConsoleWindow() {
var newConsoleWindow = window.open('consoleLog', '', 'status,height=200,width=300');
var templateContent = '<html><head><title>Console</title></head>' +
'<body><h1>Console</h1><div id="console">' +
'<span id="consoleText"></span></div></body></html>';
newConsoleWindow.document.write(templateContent);
newConsoleWindow.document.close();
return newConsoleWindow;
}
function writeToConsole(message) {
var console = getConsoleWindow();
var consoleDoc = console.document.open();
var consoleMessage = document.createElement('span');
consoleMessage.innerHTML = message;
consoleDoc.getElementById('consoleText').appendChild(consoleMessage);
consoleDoc.close();
}
jQuery.log = function (message) {
if (window.console) {
console.log(message);
} else {
writeToConsole(message);
}
};
Currently, getElementById('consoleText') is failing. Is what I'm after possible, and if so, what am I missing?
Try adding
consoleDoc.getElementById('consoleText');
right before
consoleDoc.getElementById('consoleText').appendChild(consoleMessage);
If the line you added is the one that fails, then that means consoleDoc is not right, if the next line is the only one that fails then ..ById('consoleText') is not matching up
If I don't close() the document, it appears to work as I hoped.

Problem creating an email with an attachment in Javascript

I'm initiating an email create, by calling the code below, and adding an attachment to it.
I want the user to be able to type in the receipient, and modify the contents of the message, so I'm not sending it immediately.
Why do I get a RangeError the 2nd time the method is called?
(The first time it works correctly.)
function NewMailItem(p_recipient, p_subject, p_body, p_file, p_attachmentname)
{
try
{
var objO = new ActiveXObject('Outlook.Application');
var objNS = objO.GetNameSpace('MAPI');
var mItm = objO.CreateItem(0);
mItm.Display();
if (p_recipient.length > 0)
{
mItm.To = p_recipient;
}
mItm.Subject = p_subject;
if (p_file.length > 0)
{
var mAts = mItm.Attachments;
mAts.add(p_file, 1, p_body.length + 1, p_attachmentname);
}
mItm.Body = p_body;
mItm.GetInspector.WindowState = 2;
} catch(e)
{
alert('unable to create new mail item');
}
}
The error is occuring on the mAts.add line. So when it tries to attach the document, it fails.
Also the file name (p_file) is a http address to a image.
Won't work outside of IE, the user needs to have Outlook on the machine and an account configured on it. Are you sure you want to send an email this way?
I'm trying it with this little snippet, and it works flawlessly:
var objO = new ActiveXObject('Outlook.Application');
var mItm = objO.CreateItem(0);
var mAts = mItm.Attachments;
var p_file = [
"http://stackoverflow.com/content/img/vote-arrow-up.png",
"http://stackoverflow.com/content/img/vote-arrow-down.png"
];
for (var i = 0; i < p_file.length; i++) {
mAts.add(p_file[i]);
}
Note that I left off all optional arguments to Attachments.Add(). The method defaults to adding the attachments at the end, which is what you seem to want anyway.
Can you try this standalone snippet? If it works for you, please do a step-by-step reduction of your code towards this absolute minimum, and you will find what causes the error.
first do mItm.display()
then write mItm.GetInspector.WindowState = 2;
this will work

Categories