I just wrote a chrome extension that replaces stock symbols designted with a $ before them with data from yahoo finance. I am running into some issues though based on how twitter loads the stream. I have the js set to run on document_end but twitter loads the stream after the DOM is ready. To get around this I just checked to see if a certain Element existed and then ran the scripts if it didnt just wait 500 ms and try again.
There seems to be an issue on the search pages as well possibly because the element I am checking has a different class I did not really look into the issue yet.
The other issue is it creates a mess when there are tons of symbols in one tweet might be related to the first issue but seems like it is inserting extra DOM elements.
the project is hosted on github would be awesome to get some feedback and possibly contributions.
https://github.com/billpull/Twitter-Ticker
The easiest way is to listen to DOMMutation events. Before the browser renders the tweet, you can capture this with DOMNodeInserted event.
As Chrome 18, MutationObservers are now implemented, it is fast, and doesn't fire to quickly so it is concise. DOM Mutation Observers is asynchronous and can fire multiple changes per call! It significantly improves performance of your mutations.
An example of using MutationObservers would be:
var observer = new MutationObserver(function onMutationObserver(mutations) {
mutations.forEach(function(mutationNode) {
// New Nodes added ... Deal with it!
});
});
observer.observe(historyContainerDOM, { childList: true, subtree: true });
I have added some comments to one of my open source extensions that talk about this, feel free to take what you want.
Related
I'm trying to write a userscript on Opera using Tampermonkey (although I tried ViolentMonkey already with the same results) that will run on my router's config page and calculate some values based on the statistics displayed.
The problem is, it is an .asp page, with only a frameset (no body element, although I have no idea if this is normal for asp or not, never used it) and 3 frame elements within it. After trying some DOM methods, which work but require some very inelegant approaches to actually detecting what's on the page since the url doesn't change, I stumbled upon MutationObserver which kicks ass, but I can't seem to get it to return any events, no matter what I do.
The MutationObserver works when I try it on google.com and reports normally. My code so far is just this test for MutationObserver functionality, so it's pretty much a copy/paste from here and looks like this (slightly modified):
// ==UserScript==
// #name meh
// #match http://192.168.1.1/cgi-bin/index.asp
// #run-at document-end
// ==/UserScript==
// MDN code starts here
var target = document.body;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
var config = { attributes: true, childList: true, characterData: true, subtree: true };
observer.observe(target, config);
// end of userscript
This exact code works perfectly fine on google.com. Also my #match directive isn't the problem since I log the observer to the console (not shown here) to make sure it matches the proper url.
I've tried various elements as targets (in case that was the problem) such as window.frames['framename'].document.body and the like, and I've tried with and without subtree in the configuration, as well as using document-start for the #run-at directive. No matter what, I get no mutations logged into the console.
I haven't been able to find anything online concerning this particular case so I need to ask, is there anything special about .asp pages that can mess with MutationObserver or is this something to do with frames and framesets?
edit - quite ironically, the only place online I could find to test my code other than the router's interface is The World's Worst Website. Not even jsfiddle and codepen will put up with frameset and frame.
I'm going to put this to rest. I originally wanted to approach my problem this way in order to avoid using the greasemonkey api to store values (because if I'm within a frame's context and I refresh, stored variables are wiped) and to use a more elegant and simple way of checking whether a specific frame is loaded with a specific url. Turns out browsers (Chrome, Firefox, Opera) will not spawn an event when a new url is loaded within a frame (I don't know if for iframes the behavior is the same, due to sandboxing, or iframes behave differently than ancient frames).
All in all, if you need to do something like this (maintain a variable in a userscript between refreshes of a frame), target the frame you specifically want to monitor with the #match directive and use the greasemonkey api (or whatever api your userscript extension has for storing values permanently). If you want to do this on a website you're making yourself, don't use frames (preferrably), or use postMesssage or attach event handlers where you need them.
The gist is, frames are terrible.
I'm developing a Chrome plugin. It injects a class name to every tag.
I have some problems with webpages such as facebook in which content is loaded afterwards when you scroll down.
I'd like to know if there a way to check if new content is loaded.
By now the only solution I could find is a
setInterval(function() {
Thanks.
There is a DOMSubtreeModified event (source) that Chrome supports - see this answer for details. Your code should look something like this:
document.addEventListener('DOMSubtreeModified', function() {
$("*:not(.my_class)").addClass('my_class');
}, true);
As Konrad Dzwinel said, you can use some Mutation Event listener
document.addEventListener("DOMSubtreeModified", methodToRun);
But note that the Mutation Events are performance hogs which can't really be tamed well (they fire too often and slow down the page a lot). Therefore, they have been deprecated over a year ago and should be used only when really needed. However, they work.
If you want this for a Chrome extension, you could use the new and shiny Mutation Observers from DOM Level 4 (follow the links there, they explain a lot!). Where DOMSubtreeModified fired a thousand times, MutationObserver fires only once with all the modifications contained and accessible.
Works for (as of 2012/06):
Chrome 18+ (prefixed, window.WebKitMutationObserver)
Firefox 14+ (unprefixed)
WebKit nightlies
I'm trying to debug some JavaScript, I want to find out what code gets executed when I hover over a certain div element (I've got no idea which bit of code, because there's no direct 'onmouseover' - I think there's a jQuery selector in place somewhere?).
Usually I'd use the "Break All" / "Break On Next" facility provided by Developer Tools / Firebug, but my problem is that other code (tickers, mouse movement listeners etc.) immediately gets caught instead.
What I'd like to do is tell the debugger to ignore certain JavaScript files or individual lines, so that it won't stop on code I'm not interested in or have ruled out. Is there any way to achieve that in IE (spit, spit!) - or could you suggest a better approach?
In FireFox this feature is called "Black boxing" and will be available with FireFox 25. It let's do exactly what you where looking for.
This feature was also introduced to Chrome (v30+) although it's tougher to find/configure. It's called "skip through sources with particular names" and Collin Miller did an excellent job in describing how to configure it.
Normally I'm for putting answers and howtos here instead of links but it would just end in me copying Collin's post.
Looks like you're looking for Visual Event.
You might want to take a look at Paul Irish's Re-Introduction to the Chrome Developer Tools, in particular the Timeline section (starts around 15 minutes into the video.)
You can start recording all javascript events - function executions (with source lines etc) and debug based on what events fired. There are other really handy debugging tools hiding in that google IO talk that can help you solve this problem as well.
If you're pretty sure it's a jQuery event handler you can try to poke around with the jQuery events.
This will overwrite all the click handlers (replace with the type you're interested in) and log out something before each event handler is called:
var elem = document.body; // replace with your div
// wrap all click events:
$.each($._data(elem).events.click, function(i, v) {
var h = v.handler;
v.handler = function() {
// or use 'alert' or something here if no Dev Tools
console.log('calling event: '+ i);
console.log('event handler src: '+ h.toString());
h.apply(h, arguments);
};
})
Then try calling the event type directly through jQuery to rule out that type:
$('#your_div').click()
You can use JavaScript Deobfuscator extension in Firefox: https://addons.mozilla.org/addon/javascript-deobfuscator/. It uses the same debugging API as Firebug but presents the results differently.
In the "Executed scripts" tab it will show you all code that is running. If some unrelated code is executing as well it is usually easy enough to skip. But you can also tweak the default filters to limit the amount of code being displayed.
If using are using IE 7.0 onwards, you should have developer toolbar from where you can debug. Just use breakpoint where you need, rest of the code will not stop.
Alternatavely you can define other applications like Interdev/ Visual Studio.net for debugging purpose too.
I still consider myself a novice with javascript...so be gentle :)
Is there a way to view all open events listeners on a page and perhaps to see any inifinte loops that may be running?
What is happening, is a page I'm trying to debug works fine. Nodes get added to the page dynamically via a drag and drop method. All works well, but as time goes on, it seems to get increasingly slower - meaning the mouse starts skipping and the such.
I don't know if this is because javascript stores stuff in memory and my memory is getting used up, or if because of the constant checking of elements on mousemove slows things down as more elements are added to the page.
So I thought I would ask what I thought to be the obvious of maybe eventListeners are piling up and I'm not realizing it, or maybe there is an inifinte loop that is not being closed out.
I have firebug, and feel like I've looked at everything. I've put in console.debug statements in the loops and they all seem to end fine.
Any debugging tips would be appreciated.
I would say definitely be careful of memory leaks, especially in IE.
Here's a good resource for learning Javascript:
www.javascriptkit.com
Specifically here are some useful articles:
http://www.javascriptkit.com/jsref/events.shtml
http://www.javascriptkit.com/javatutors/closuresleak/index.shtml
What you need is a JavaScript profiler. Google chrome has a built in under ctrl-shift-j > profiles. There is one available in firebug for firefox as well.
Last week we released Omniture's analytics code onto a large volume of web sites after tinkering and testing for the last week or so.
On almost all of our site templates, it works just fine. In a few scattered, unpredictable situations, there is a crippling, browser-crashing experience that may turn away some users.
We're not able to see a relationship between the crashing templates at this time, and while there are many ways to troubleshoot, the one that's confuddling us is related to event listeners.
The sites crash when any anchor on these templates is clicked. There isn't any inline JS, and while we firebug'ed our way through the attributes of the HTML, we couldn't find a discernable loop or issue that would cause this. (while we troubleshoot, you can experience this for yourself here [warning! clicking any link in the page will cause your browser to crash!])
How do you determine if an object has a listener or not? How do you determine what will fire when event is triggered?
FYI, I'd love to set breakpoints, but
between Omnitures miserably obfuscated code and repeated browser
crashes, I'd like to research more
thoroughly how I can approach this.
I did an "inspect element" on a link in that page with firebug, and in the DOM tab it says there is an onclick function (anonymous), and also some other function called "s_onclick_0".
I coaxed firebug placing a watch like
alert(document.links[0].onclick)
to alert me the onclick function that omniture (i guess) attaches to links:
function anonymous(e) {
var s = s_c_il[0], b = s.eh(this, "onclick");
s.lnk = s.co(this);
s.t();
s.lnk = 0;
if (b) {
return this[b](e);
}
return true;
}
Maybe in the same way you can see what it is really running after all that obfuscation.
DOM doesn't provide any means to introspecting through the events listeners' collections associated with a node.
The only situation where listener can be identified is when it was added through setting a property or an attribute on the element - check on onxxx property or attribute.
There have been a talk recently on WebAPI group at W3 on whether to add this functionality. Specialists seem to be against that. I share their arguments.
A set of recommendations to the implementers of on-page analytics:
Use document-level event capturing only, this is in almost every case (besides change/submit events) sufficient
Do not execute computation-intensive code (as well as any IO operations) in the handlers, rather postpone execution with a timeout
If this two simple rules are taken into account, I bet your browser will survive
I have some experience with Omniture and looking at your s_code.js, you have several things going on in the "Link Tracking" area, for example:
/* Link Tracking Config */
s.trackDownloadLinks=true
s.trackExternalLinks=true
s.trackInlineStats=true
s.linkDownloadFileTypes="exe,zip,wav,mp3,mov,mpg,avi,wmv,pdf,doc,docx,xls,xlsx,ppt,pptx"
s.linkInternalFilters="javascript:,gatehousemedia.com"
s.linkLeaveQueryString=false
s.linkTrackVars="None"
s.linkTrackEvents="None"
I would consult with the people at Omniture and verify that your link tracking configuration is set up correctly.
Specifically, this template and the links inside seem to belong to morningsun.net and yet morningsun.net is not in the s.linkInternalFilters setting. If you are using the same s_code.js file for multiple domains, you can use javascript to set the configuration values for things like this (basing on the document.location.hostname for instance).
I don't personally have experience with the link tracking configuration or I would give you more detail on how to configure it :)
While traveling home I came to a solution that allows for introspection of event handlers on element added with AddEventListener. Run code before the inclusion of your analytics code. The code was not verified if works, but the idea, I guess is clear. It won't work in IE, however you can apply similar technique (of rewriting the API member) there as well.
(function(){
var fAddEventListener = HTMLElement.prototype.addEventListener;
HTMLElement.prototype.addEventListener = function() {
if (!this._listeners)
this._listeners = [];
this._listeners.push(arguments);
fAddEventListener.apply(this, arguments);
}
})();