summaryrefslogtreecommitdiff
path: root/chrome/content_script.js
blob: 3e5621e47d99139df5b3e59c65c93060ca0b85fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function zgGetContentTypeFromHeader() {
	var nodes = document.getElementsByTagName("meta");
	for (var i=0; i<nodes.length; i++)
	{
		var node = nodes[i];
		if (!node.hasAttributes()) continue;
		var http_equiv = node.getAttribute("http-equiv");
		if (http_equiv && http_equiv.toLowerCase() == "content-type")
		{
			var content_type = node.getAttribute("content");
			if (!content_type) continue;
			return content_type.split(';')[0];
		}
	}
	return null;
}

function zgGetDocumentInfo () {
	var docInfo = {
		"url": document.URL,
		"origin": document.referrer,
		"title": document.title
	};

	if (document.domain) {
		docInfo["domain"] = document.location.protocol + "//" + document.domain;
	}

	var contentType = zgGetContentTypeFromHeader();
	if (contentType) {
		docInfo["mimeType"] = contentType;
		chrome.extension.sendRequest(docInfo);
	} else {
		// send extra request to get the mime type
		var request = new XMLHttpRequest();
		request.open("HEAD", document.URL, true);
		request.onreadystatechange=function() {
			if (request.readyState==4) {
				var content = request.getResponseHeader("Content-Type");
				if (!content) return;
				docInfo["mimeType"] = content.split(';')[0];
				chrome.extension.sendRequest(docInfo);
			}
		}
		request.send(null);
	}
}

/*
function zgReadyStateChanged () {
	console.log("ready state change fired! " + document.readyState);
	if (document.readyState == "complete") {
		zgGetDocumentInfo();
		document.removeEventListener("readystatechange", zgReadyStateChanged, false);
	}
}*/

function zgTimeoutElapsed () {
	if (document.readyState == "complete") {
		zgGetDocumentInfo();
	} else {
		window.setTimeout(zgTimeoutElapsed, 1000);
	}
}

if (document.readyState != "complete") {
	// in a perfect world this would work
	//document.addEventListener("readystatechange", zgReadyStateChanged, false);
	// in real world we have to be nasty
	window.setTimeout(zgTimeoutElapsed, 1000);
} else {
	zgGetDocumentInfo();
}