-
Notifications
You must be signed in to change notification settings - Fork 3
/
example_usage.js
103 lines (94 loc) · 3.23 KB
/
example_usage.js
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
var AndroidWebPrint = function (useHttps, checkRelay, relayhost, relayport) {
var usehttps = false;
var relayHost = "127.0.0.1";
var relayPort = "8080";
this.print = function (data) {
if (!usehttps){
sendHttpData(data);
}
if (!pwindow || pwindow.closed) {
openPrintWindow();
setTimeout(function () {
sendData(data);
}, 220);
}
sendData(data);
};
function sendData(data) {
pwindow.postMessage(data, "*");
}
var pwindow;
function openPrintWindow() {
pwindow = window.open("http://" + relayHost + ":" + relayPort + "/printwindow", 'AndroidPrintService');
pwindow.blur();
window.focus();
}
var timeOut;
this.checkRelay = function () {
if (!usehttps){
checkHttpRelay();
return;
}
if (pwindow && pwindow.open) {
pwindow.close();
}
window.addEventListener("message", message, false);
openPrintWindow();
timeOut = setTimeout(dispatchAndroid, 2000);
};
function message(event) {
if (event.origin != "http://" + relayHost + ":" + relayPort)
return;
if (event.data=="init"){
clearTimeout(timeOut);
alert("The Android print service has been loaded in a new tab, keep it open for faster printing.");
}
}
function dispatchAndroid() {
var answer = confirm("Would you like to open/install the printing app?");
if (answer) {
document.location.href = "https://wallaceit.com.au/playstore/httpsocketadaptor/index.php";
}
}
function sendHttpData(data) {
try {
data = encodeURI(data);
var response = $.ajax({
url: "http://" + relayHost + ":" + relayPort,
type: "POST",
data: data,
processData: false,
crossDomain: true,
crossOrigin: true,
timeout: 2000,
async: false
});
return response.status == 200;
} catch (ex) {
alert("Error sending data to the socket relay.");
return false;
}
}
function checkHttpRelay() {
$("#printstat").show();
$.ajax({
url: "http://" + relayHost + ":" + relayPort,
type: "GET",
crossDomain: true,
crossOrigin: true,
timeout: 2000,
success: function () {
},
error: function () {
dispatchAndroid();
}
});
}
if (relayhost) relayHost = relayhost;
if (relayport) relayPort = relayport;
if (checkRelay) this.checkRelay();
return this;
};
// usage
var webprint = new AndroidWebPrint(true, true, null, null);
webprint.print("some raw socket data");