JavaScript talking to Flash via ExternalInterface - javascript

I have been trying to put together a proof of concept of JavaScript talking to Flash. I am using JQuery and Flash CS5, ActionScript 3.
I am not a Flash developer so apologies for the code, if I can prove this works the Flash will be given to someone who knows what they are doing.
The Actionscript is on a layer in the timeline in the first frame, with a couple of elements in the root movie:
output = new TextField();
output.y = -200;
output.x = -200;
output.width = 450;
output.height = 325;
output.multiline = true;
output.wordWrap = true;
output.border = true;
output.text = "Initializing...\n";
root.bgClip.addChild(output);
try{
Security.allowDomain("*");
flash.external.ExternalInterface.marshallExceptions = true;
output.appendText("External Interface Available? " + ExternalInterface.available + "\n");
output.appendText("External Interface ObjectId: " + ExternalInterface.objectID + "\n");
flash.external.ExternalInterface.addCallback("getMenuItems", returnMenuItems);
flash.external.ExternalInterface.addCallback("changeText", changeText);
flash.external.ExternalInterface.addCallback("changeBgColour", changeBgColour);
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
} catch (error:SecurityError) {
output.appendText("Security Error: " + error.message + "\n");
} catch (error:Error) {
output.appendText("Error: " + error.message + "\n");
}
function returnMenuItems():String{
return "[{\"menu option\": \"javascript:callFlash('changeBgColour','4CB9E4')\"}]";
}
function changeText(t:String){
root.textClip.text = t;
}
function changeBgColour(colour:String) {
var c:ColorTransform = root.bgClip.transform.colorTransform;
c.color = uint(colour);
root.bgClip.transform.colorTransform = c;
}
The JavaScript and HTML are:
function populateMenu(message){
$("#options").changeType("Options", $.parseJSON(message));
$("#options").addMenuActions();
}
function callFlash(methodToCall, param){
alert("method: " + methodToCall + ", param: " + param);
if(param == undefined){
$("#AJC")[methodToCall]();
}else{
$("#AJC")[methodToCall](param);
}
}
var flashvars = {};
var params = {allowScriptAccess: "always"};
var attributes = {name: "AJC"};
swfobject.embedSWF("http://192.168.184.128/ActionscriptJavascriptCommunication.swf", "AJC", "600", "400", "9", "", flashvars, params, attributes);
and
<body>
<div id="wrapper">
<div id="topBar" class="top-bar"></div>
<div id="flashContainer">
<div id="AJC">Loading Flash...</div>
</div>
<ul class="dropdown" id="games"></ul>
<ul class="dropdown" id="options"></ul>
</div>
</body>
Now I know the ActionScript is awful, the reason it looks like it does is because I have read a lot of threads about possible issues to do with contacting Flash from JavaScript (hence the allow security domain * and adding a debug text box etc).
The JavaScript I am using is within a script tag in the head. The changeType and addMenuActions are just JQuery methods I have added. These are just JavaScript methods that have been tested independently but do work.
You'll notice that the last line of my try catch in the ActionScript is:
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
This does work, it populate my menu with the text sent from Flash. The only thing that doesn't work is trying to call the methods exposed using the addCallback function.
I get the alert which says:
method: changeBgColour, param: 4CB9E4
but an error saying:
Error: $("#AJC")[methodToCall] is not a function
Source File: http://192.168.184.128/test.html#
Line: 88
I set up a local VM to run Apache, which relates to the 192.168.184.128, I wondering if this was the issue, I have seen a couple of threads mention that trying to communicate with flash locally won't work, which is why I set up the VM with apache?
Any ideas? I know people have got this working, it is very frustrating.
Thanks.

Simple mistake: jQuery's factory method produces jQuery.init object, which acts very similar to an array. You need to call the method on the actual DOM element, which is the first member in the "array".
$('#AJC')[0][methodToCall]
If you had security issues, you wouldn't be able to communicate between Flash and JavaScript at all.

The problem is in the way you are accessing your flash object. SwfObject has a built-in function that take care of that, it works great across all browsers:
function callFlash(methodToCall, param)
{
var obj = swfobject.getObjectById("AJC");
if(param == undefined){
$(obj)[methodToCall]();
}else{
$(obj)[methodToCall](param);
}
}
I havent tested the code above, but I guess it should work!

Related

Javascript redirect using windows.locaton.href OR windows.locaton.replace is not working. Error: window not defined

I have looked at all of the questions around windows.locaton.href and windows.locaton.replace not working, but still can't figure out why this redirect is not working in JavaScript. There are two JS functions I am calling when a button is clicked with submit.
<input type="submit"
onclick="NotifyUserOfNewBudgets('#Field1');redirect2MainLookup('#primaryFilename');"
class="SaveChangeButton" value="Create New Budget">
The two functions are defined in Javascript as:
<script>
function NotifyUserOfNewBudgets(val) {
alert("New Budget will be saved. NewVal=" + val);
var ireturn;
document.getElementById("NewBudgetID").value = val;
document.getElementById("formMode").value = "Update";
}
function redirect2MainLookup(primaryFilename) {
var loc = window.location.pathname;
var host = document.location.host;
var dir = loc.substring(0, loc.lastIndexOf('/'));
//Replace the word Edit with blank so this redirects correctly
var newdir = dir.replace("NewBudget", "");
var newpath = host + newdir + primaryFilename;
alert('newpath location = http://' + newpath);
try {
windows.locaton.href = "http://" + newpath;
//window.location.replace('http://' + newpath);
} catch (err) { alert("Error: " + err);}
}
</script>
The error I get in the try()catch() is windows is not defined and then is stays on the same page. I get the same error using windows.locaton.replace() too. I have lots of pages doing redirects, can't figure out why this one fails.
You have a number of spelling mistakes. window is the object you are looking to reference. location is the property you are looking to access. Right now, you are using windows.locaton. windows is not a thing, nor is locaton. Keep an eye on undefined errors, they can tell you a lot about the state of your code.

Multiple JavaScripts - Both work separately, but if used together second doesn't do anything

I am trying to load 2 scripts (or more) on one page and Only the 1st one is working. I do not have access to edit the javascript so I cannot make changes to it.
Here is the code:
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269"></script>
<noscript></noscript>
</div>
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175270"></script>
<noscript></noscript>
</div>
When I run the page, the 1st one loads fine but the second one does not. Any help is greatly appreciated.
Jsfiddle links:
Not working: http://jsfiddle.net/6E6ZC/
Working seperately 1: http://jsfiddle.net/5LZ8d/
Working seperately 2: http://jsfiddle.net/SQ778/
DO NOT REMOVE CACHE.
What is happening is that the browser thinks it is being asked to retrieve the same file on each request.
I had the same issue and here is how to resolve it.
Add one more querystring paramater like I have. I added the '&t='+ new Date().getTime()
'/api/drawings?a=e&f=img&id=' + eID + '&t=' + new Date().getTime()
Will work like a champ!
Here is a way to dynamically add the scripts to the page, and this is a FOR SURE WILL WORK WAY.
<script type="text/javascript">
setTimeout(function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script');
script1.setAttribute('type', 'text/javascript');
script1.setAttribute('id', 'script1');
script1.setAttribute('src', 'http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269&t=' + new Date().getTime());
script1.setAttribute('type', 'text/javascript');
script1.setAttribute('id', 'script2');
script1.setAttribute('src', 'http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269&t=' + new Date().getTime());
document.getElementsByTagName("head")[0].appendChild(script1);
document.getElementsByTagName("head")[0].appendChild(script2);
},500);
</script>
**With the script above you do not have to add the scripts statically. Just let the script that I've provided run.
This is all assuming that you're not attempting to load two JS files with the same exact script in each file. If your trying to continually check for changes you only need one file and an interval. "setInterval(function(){//this would be something totally different and a lot more work})"
You may have a caching problem. Try setting headers on the JavaScript so that it doesn't allow browser caching.
There is no caching problem and both scripts load correctly with a http 200 status message. When used separately, they produce results but when used together the 2nd one doesn't produce any result.
This could be happening as 2nd script expects something in the page where it can put its contents, but it doesn't find there s it was removed by 1st script. This looks to me as the most probable cause.
Example:
http://jsfiddle.net/6E6ZC/
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269"></script>
<noscript></noscript>
</div>
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175270"></script>
<noscript></noscript>
</div>
Okay, I feel bound to answer this one after seeing so many wrong turns.
Cache or not is a non-issue. Even if the browser does cache the request (and it most likely will, since the URLs are exactly the same), it all depends on what the loaded code is supposed to do.
Unless the code changes the name of its functions and/or variables on the fly or does other very smart things, including basically the same code a second time will very likely overwrite the first copy, thus doing nothing more than if the file had been included only once.
I would be very surprised if the guys at http://tickettransaction.com did design an interface relying on the user adding some random junk at the tail of the URL to allow a second execution of the very same request result on the same page.
Would they have wanted to support such an usage, they would simply have added a cache-control: no-cache or equivalent directive in their response headers.
But after all, I've seen weirdest things in my programmer's life.
Maybe the guy at tickettransaction.com was badly hungover the day he coded that or something?
To get rid of this cache false problem, simply open your dev tools and watch the network traffic. You will most likely see the request being fetched twice from the cache (or once from the server and once from the cache if you hit Ctrl+F5).
If you really want to have your request fetched twice from the server, simply disable the cache, and make sure you get a full server transfer twice.
Having jumped through all these hoops, you will very likely witness the same result, namely the second response code overwriting the first.
Last update.
Just to get rid of this caching non-issue, I added a variable parameter in the URL.
I used the dev tools to make sure the browser was NOT caching the second request.
Cache being dealt with once and for all, I did have a look at the code of this mysterious script:
document.write('<!--MA-WS-C23-->');
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/jquery_tn.js"></' + 'script>');
document.write('');
var TN_ticketResults = null;
function TN_populateTicketData(data) {
TN_ticketResults = data;
if(typeof TN_tryCreateTicketTable == "function")
TN_tryCreateTicketTable();
}
(function() {
var cysct = document.createElement("script");
cysct.type = "text/javascript";
cysct.src= '//tickets.tickettransaction.com/Tickets/ByEvent/?' +
'eventId=2175270&websiteConfigId=669&sort=retail&callback=TN_populateTicketData';
cysct.async = true;
var pnode = document.getElementsByTagName('script')[0];
pnode.parentNode.insertBefore(cysct, pnode);
})();
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/swfobject_tn.js"></' + 'script>');
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/maincontrol_tnservice_tn.js" ></' + 'script>');
document.write('');
// ppcsrc
var cookie_tn_ppc_src ='';
var tn_cookies = '; '+document.cookie + ';';
var cookie_ppc_src_start =tn_cookies.indexOf('; tn_ppc_src=') + 13;
if(cookie_ppc_src_start != 12)
cookie_tn_ppc_src = '&ppcsrc=' + tn_cookies.substring(cookie_ppc_src_start, tn_cookies.indexOf(';', cookie_ppc_src_start));
var acct_start =tn_cookies.indexOf('; rcaid=') + 8;
if(acct_start != 7)
cookie_tn_ppc_src +='&rcaid=' + tn_cookies.substring(acct_start, tn_cookies.indexOf(';', acct_start));
//map css suppliment
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute('href', 'http://seatics.tickettransaction.com/tnservice_map_suppliment_tn.css');
document.getElementsByTagName('head')[0].appendChild(fileref);
//maps
var webParms = {
swfMapURL : "http://seatics.tickettransaction.com/FenwayPark_Baseball_2013-04-24_2013-04-24_1120_tn.swf",
staticMapURL : "http://seatics.tickettransaction.com/FenwayPark_Baseball_2013-04-24_2013-04-24_1120_tn.gif",
mapShellURL : 'http://seatics.tickettransaction.com/mapshell_tn.swf'
};
webParms.vfsFilterAnimate = 'vertical-list';
webParms.vfsImageAnimate = 'vertical-list';
webParms.vfsEnable = 'selected-hover';
var TN_docFinishedLoading = false;
window.onload = function() {
ssc.EH.buyTickets = function(buyObj) {
var purchaseUrl = 'https://tickettransaction2.com/Checkout.aspx?wcid=669&e=' + escape(buyObj.tgSds) + cookie_tn_ppc_src + '&treq=' + buyObj.buyQty + '&SessionId=' + makeGuid();
if (typeof AppendToPurchaseUrl == "function") {
try {
purchaseUrl = AppendToPurchaseUrl(purchaseUrl);
} catch(e) {
}
}
if (typeof PopupCheckOut == "function" && PopupCheckOut())
window.open(purchaseUrl, '_blank', 'location=no,scrollbars=yes,resizable=yes,menubar=yes,toolbar=yes');
else
location.href = purchaseUrl;
};
TN_docFinishedLoading = true;
TN_tryCreateTicketTable();
};
var TN_onEmptyEvent = TN_onEmptyEvent || function(title) {
$("#tn_loading").css("display", "none");
$("#ssc_listAndMapDiv").css("display", "none");
$("#tn_tblNoResults").css("display", "");
};
function TN_tryCreateTicketTable() {
if (TN_docFinishedLoading && TN_ticketResults) {
if (TN_ticketResults.TicketsAvailable) {
$("#tn_loading").css("display", "none");
ssc.loadTgList(TN_ticketResults.TicketData, webParms);
} else {
TN_onEmptyEvent('Boston+Red+Sox+vs.+Tampa+Bay+Rays+on+Tue%2c+Apr+29+2014');
}
}
}
function makeGuid() {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var guidLength = 5;
var guid = '';
for (var i = 0; i < guidLength; i++) {
var rnum = Math.floor(Math.random() * chars.length);
guid += chars.substring(rnum, rnum + 1);
}
return guid;
}
function GoToOtherGame(eventid) {
if (eventid != '')
document.location = 'ResultsTicket.aspx?evtid=' + eventid;
}
document.write('<table class="tn_results_header"> <tr class="tn_results_header_title"> <td class="tn_results_header_title"> Boston Red Sox vs. Tampa Bay Rays </td> <td class="tn_results_header_venue"> Fenway Park <br /> Boston, MA </td> <td class="tn_results_header_datetime"> Tue, Apr 29 2014 <br /> 7:10 PM </td> </tr> <tr class="tn_results_header_divider"> <td colspan="3" class="tn_results_header_divider"> </td> </tr></table> <div id="tn_loading" style="text-align:center;"><img src="//s3.amazonaws.com/TNService/Images/spinner.gif"/></div><div id="ssc_listAndMapDiv"></div><table style="display: none;" id="tn_tblNoResults" class="tn_results_notfound" cellspacing="0" cellpadding="4"> <tr class="tn_results_notfound"> <td class="tn_results_notfound"> There is currently no online inventory available for this event. <br /> <br /> Please contact <span class=\'tn_results_notfound_name\'> TicketSociety.com</span> at <span class="tn_results_notfound_phone"> (866) 459-9233</span> or <a class="tn_results_notfound_email" href="mailto:CustomerSupport#TicketSociety.com"> CustomerSupport#TicketSociety.com</a> to check availability for this event. </td> </tr> <tr valign="middle" class="tn_results_divider"> <td class="tn_results_divider"> </td>');
document.write(' </tr></table>');
As expected, it does some inline Javascript that actually WORKS twice. You can see it when looking at the 2 lines header before the big table. They indeed appear twice.
You can also inspect the DOM and you will see that your second div is populated with a skeleton table, but the table is never filled.
Unfortunately, the code also defines some variables and functions that are overwritten by the second include. The result is an Ajax request that cannot succeed (basically because the code was not designed to handle the same Ajax request twice on the same page).

Brightcove Video Manager API, Get Playlist by ID java script

I am pretty new to the whole idea of java script and am really stuck trying to find a solution to my problems. I have fallowed the template that brightcove uses for the video manager which uses a "get all playlist URL" call. I am trying to just make a menu of just a few specific playlist and am getting error after error when doing so, no matter what I change. As of right now my my main error is "Uncaught TypeError: Cannot read property 'length' of undefined".Any help would be so greatly appreciated. Thank you.
//Get PlayList by ID
function getPlaylistLindyURL(){
loadStart();
paging.playlistbyid = (paging.currentFunction == getPlaylistLindyURL)?paging.generic:paging.playlistbyid;
paging.currentFunction = getPlaylistLindyURL;
return apiLocation +
'?command=find_playlist_by_id&playlist_id=1990786315001&callback=showPlaylistByIDCallBack'
+ '&get_item_count=true&page_size=' + paging.size + '&page_number='+paging.playlistbyid
+'&token='+readToken;
//Playlist by ID callback
function showPlaylistByIDCallBack(o){
if(null == o.error){
oCurrentMainVideoList = o.items;
buildMAinVideoList();
doPageList(o.total_count, "Videos");
}else{
var message = (null!=o.error.message)?o.error.message:o.error;
alert("Server Error: "+ message);
}
loadEnd();
}
//For PlayList by ID
function buildMAinVideoList() {
//Wipe out the old results
$("#tbData").empty();
// Display video count
document.getElementById('divVideoCount').innerHTML = oCurrentMainVideoList.length + "Video";
document.getElementById('nameCol').innerHTML = "Video Name";
document.getElementById('headTitle').innerHTML = "All Videos";
document.getElementById('search').value = "Search Videos";
document.getElementById('tdMeta').style.display = "none";
document.getElementById('searchDiv').style.display = "none";
document.getElementById('checkToggle').style.display = "none";
$("span[name=buttonRow]").hide();
$(":button[name=delFromPlstButton]").hide();
//For each retrieved video, add a row to the table
var modDate = new Date();
$.each(oCurrentMainVideoList, function(i,n){
modDate.setTime(n.lastModifiedDate);
$("#tbData").append(
"<tr style=\"cursor:pointer;\" id=\""+(i)+"\"> \
<td>\
<input type=\"checkbox\" value=\""+(i)+"\" id=\""+(i)+"\" onclick=\"checkCheck()\">\
</td><td>"
+n.name +
"</td><td>"
+(modDate.getMonth()+1)+"/"+modDate.getDate()+"/"+modDate.getFullYear()+"\
</td><td>"
+n.id+
"</td><td>"
+((n.referenceId)?n.referenceId:'')+
"</td></tr>"
).children("tr").bind('click', function(){
showMetaData(this.id);
})
});
From the code you posted it looks like oCurrentMainVideoList is not declared any where, so that might be why its saying its undefined...
If you have it defined as a global variable which it must be from the look of it, make sure you have sett a value to it. But you should not use a global variable, create a namespace for your functions, it helps with scope control.
If you want to learn some JS best practices you should watch this video from TekPub:
JS_UpToSpeed
You should also take your time to look over your code and make it more readable before you post, the lack of indentations is making the code hard to read and theres multiple capital letters in buildMAinVideoList.

Channel messaging on HTML 5 with Javascript

I have a problem with the messaging channel in HTML 5
On one side I have the code:
<iframe id="ifr" src="receive.html" onLoad="initMessaging()" ></iframe>
<button onClick="postMsg()">Wyslij</button>
<script type="text/javascript">
var channel = new MessageChannel();
channel.port1.onmessage = function (evt) {
alert(evt.origin + ": " + evt.data);
};
function initMessaging() {
var child = document.getElementById("ifr");
child.contentWindow.postMessage('hello', 'http://localhost:85', [channel.port2]);
}
function postMsg() {
channel.port1.postMessage('Message sent from ' + location.host);
}
And on second site:
<input type="button" value="Post Message" onClick="postMsg();" />
<script type="text/javascript">
var port = null;
window.addEventListener("message", function (e) {
port = e.ports[0];
port.onmessage = function (e){
port.addEventListener("message", function (evt) {alert("Received message \"" + evt.data + "\" from domain: " + evt.origin);
}, false);
}
}, false);
function postMsg() {
if(port) {
port.postMessage("Data sent from " + location.host);
}
Why Its doesnt working? What I do wrong?
Thx a lot for help!
I think you need to use a form to call the postMessage function and send the message. Here's a tutorial that shows a simpler way of getting this done.
HTML5 postMessage interface is not good. I propose an intuitive one. you can download it from my site:
http://www.jackiszhp.info/tech/postMSG.html
window.MSG.post(msgname, msgdata, arrayOfDomainTarget, arrayOfWindowIDTarget)
this 'window' can be omit, not similar to the one specified in HTML5
there you need an window object.
Here, you do not. this 'window' just indicate MSG is in the global space.
msgname is the the name the message category.
msgdata is a JSON object. it will be stringified before post
arrayOfDomainTarget, arrayOfWindowIDTarget
I use logical AND. originally it was OR
later I changed it to AND. more appropriate. I guess.
and I let "*" to be the wildcard for all windowID.
the caller's information does not present in the parameter at all
since the browser knows all the information.
so we can see that this method does not allow the sender to fool the receiver.
the sender just call as follows.
window.name="myWindowID";
MSG.post("cmd",{what:'do thing abc',parameter:'the value of a parameter'},["jackiszhp.info"],[*]);
for the receiver, 2 things.
//#1 define the message handler
function messageHandler(e){
var obj=JSON.parse(e.detail);
obj.name is the msgname = 'cmd'
obj.data is the msgdata = {what:'fuck',who:'not to tell'};
obj.source is the sender
obj.source.href is the sender's window.location.href
obj.source.WID is the sender's window.name="myWindowID";
obj.target is the target of this event
obj.target.domains is the target domains of this event
obj.target.WIDs is the target WIDs of this event
....
}
//#2 register the message handler
window.addEventListener(msgname, messageHandler,false);
or
document.addEventListener(msgname, messageHandler,false);
//to respond,
window.name="hereMywindowID";
MSG.post("cmd",{what:'do thing def',parameter:'the value of a parameter'},["jackiszhp.info"],['myWindowID']);
//clearly, we can see that this response only the original sender can receive it.
//unless in the target domain, accidently, there are two windows with same ID "myWindowID".
Additional note:
A. window can be uniquely identified. but here, I did not use it. I use window.name instead. about window ID, you can check this link: https://developer.mozilla.org/en-US/docs/Code_snippets/Windows#Uniquely_identifying_DOM_windows
B. I hope the mozilla can take my interface and include it into the firefox.

Try catch error in Javascript pass the error statment into Google Analytics

I have a Toogle function that uses to show/hide a div bloack to end users. However, some users said the IE generate an error when they clicks on this link. I am wondering whether I can use try catch statement in JavaScript to catach the error the users got and send to Googel Analytics.
If Yes, How I can do that. I have google analytcis set up in our site.
For instance, I have a div section call dynamic phone number.
<div id = "cs_DynamicForm">
"Phone number..."
<div>
When users click on Phone us link, i am able to track it in google.
<a onclick="javascript: pageTracker._trackPageview('/Contact/UK/phone');" id="phoneNumberToggle" class="more-info-link" href=" javascript:void(0);">Phone us</a>
In the back end, my toggle function works, like that
_dynamicPhoneNumber: function(type, arg)
{
var phoneNumber = document.getElementById("cs_DynamicForm");
var vis =phoneNumber.style;
//alert(vis);
if(vis.display==''&&phoneNumber.offsetWidth!=undefined&&phoneNumber.offsetHeight!=undefined)
vis.display = (phoneNumber.offsetWidth!=0&&phoneNumber.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
If i have to rewrite this function, i think it will look likes that:
try{
var phoneNumber = document.getElementById("cs_DynamicForm");
var vis =phoneNumber.style;
//alert(vis);
if(vis.display==''&&phoneNumber.offsetWidth!=undefined&&phoneNumber.offsetHeight!=undefined)
vis.display = (phoneNumber.offsetWidth!=0&&phoneNumber.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
catch (e)
{
var errorMsg=e.message;
if (typeof (e.number) != "undefined") {
document.write ("<br />");
document.write ("The error code: <b>" + e.number + "</b>");
}
if (typeof (e.lineNumber) != "undefined") {
document.write ("<br />");
document.write ("The error occurred at line: <b>" + e.lineNumber + "</b>");
}
//And send the errorMsg to google analytics. how I should do that
}
Any helps,
Cheers,
Qing
first catch the error simply like:
try {
tes.ting = 123;
}
catch(e) {
errors.push(e);
}
then push it to Google
_gaq.push(['_trackEvent', 'Testing', 'Error', errors.toString()]);
You can use the trackEvent as has been pointed here - but I believe the easiest way is to use trackPage, as you did for the other pages.
I use something like this:
try {
...
} catch (e)
{
pageTracker._trackPageview('/errors/'+e.toString());
}
You can replace 'errors/' with whatever makes sense to you ('virtual-errors-list/' for example).
In addition, consider adding the error tracking to window.onerror handler:
window.onerror = function(errorMsg, url, lineNumber){
pageTracker._trackPageview('/errors/'+errorMsg);
}

Categories