Skip to content
Browse files

Catch more types of Youtube URLs and more dynamically generated HTML.

  • Loading branch information...
1 parent bca0694 commit 44238fe37860476227d0ee098b2006570691522f @divergentdave committed Feb 20, 2012
Showing with 19 additions and 15 deletions.
  1. +19 −15 youtube_preview/youtube_preview.user.js
View
34 youtube_preview/youtube_preview.user.js
@@ -4,10 +4,9 @@
// @description Fetch the description for Youtube links, and put it in the hover text
// @include *
// ==/UserScript==
-
(function () {
-var regex = /watch\?v=([-_a-zA-Z0-9]*)/;
-var xpath = "//a[starts-with(@href,'http://www.youtube.com/watch?')]";
+var regex = /watch\?(?:.*=.*&)*v=([-_a-zA-Z0-9]*)/;
+var xpath = "descendant-or-self::a[starts-with(@href,'http://www.youtube.com/watch?') or starts-with(@href,'https://www.youtube.com/watch?')]";
function die(str) {
alert(str);
@@ -19,7 +18,7 @@ function process(tag) {
if (id.length < 3) die("Strange YouTube ID: " + id);
GM_xmlhttpRequest({
method: 'GET',
- url: 'http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2',
+ url: 'https://gdata.youtube.com/feeds/api/videos/' + id + '?v=2',
onload: function (details) {
if (details.status != 200) return;// Video no longer exists
var parser = new DOMParser();
@@ -29,25 +28,30 @@ function process(tag) {
var title = titles[0];
if (title.childNodes.length != 1) die("Didn't find one child node of <title>");
var textNode = title.firstChild;
- if (textNode.nodeType != 3 /*Node.TEXT_NODE*/) die("Non-text node found, was of type " + textNode.nodeType);
+ if (textNode.nodeType != Node.TEXT_NODE) die("Non-text node found, was of type " + textNode.nodeType);
tag.setAttribute('title', textNode.nodeValue);
}
});
}
-var tags = document.evaluate(xpath, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
-for (var i = 0, tag = null; (tag = tags.snapshotItem(i)); i++) {
- process(tag);
+function processTree(base) {
+ // have to use snapshot over iterator because we modify the DOM in between accesses
+ var tags = document.evaluate(xpath, base, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
+ for (var i = 0, tag = null; (tag = tags.snapshotItem(i)); i++) {
+ process(tag);
+ }
}
+processTree(document);
+
document.addEventListener('DOMNodeInserted', function(event) {
- if (event.target.nodeType != Node.ELEMENT_NODE) return;
- if (event.target.tagName.toUpperCase() != 'A') return;
- var url = event.target.getAttribute('href');
- if (!url) return;
- if (url.indexOf('http://www.youtube.com/watch?') != 0) return;
- process(event.target);
+ processTree(event.target);
+}, false);
+
+document.addEventListener('DOMAttrModified', function(event) {
+ if (event.attrName == 'href') {
+ processTree(event.target);
+ }
}, false);
-//TODO: Hook other events to catch when <a> tags are given new hrefs
})();

0 comments on commit 44238fe

Please sign in to comment.
Something went wrong with that request. Please try again.