-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbookmarklet.js
90 lines (77 loc) · 2.21 KB
/
bookmarklet.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
(function(){
'use strict';
let proxy = 'https://cors-anywhere.herokuapp.com/';
let host_regex = 'https?://.*';
let _scope = function(scope){
this.dependencies = []
this.scope = scope
this.load = function(url){
let script = document.createElement('script');
script.src = url;
let p = new Promise((resolve,reject)=>{
script.onload = resolve;
script.onerror = function(){reject(url)};
});
scope.appendChild(script);
this.dependencies.push(p);
}
this.run = async function(func){
await Promise.all(this.dependencies).catch(function(error) {
let emsg = `Dependency '${error}' failed to load`;
alert(emsg);
throw emsg;
});
let script = document.createElement('script');
script.text = `(function(){let proxy='${proxy}'; (${func.toString()})()})()`;
scope.appendChild(script);
}
}
let local_scope = async function(){
let scope = new _scope(document.body);
return scope
}
let iframe_scope = async function(){
let iframe = document.createElement("iframe");
iframe.style.display = "none";
let loaded = new Promise((resolve,reject)=>{iframe.onload = resolve});
document.body.appendChild(iframe);
await loaded;
let scope = new _scope(iframe.contentDocument.body);
return scope;
}
let bookmarklet = async function(dependencies, func, scope=iframe_scope){
if (!location.href.match(host_regex)){
if (!confirm(`Current url doesn't match host regex:\n${host_regex}\n\nContinue?`))
return
}
let iframe = await scope();
for (let dependency of dependencies){
iframe.load(dependency);
}
iframe.run(func);
return iframe;
}
// testcases here
// test1.js, test2.js, test3.js are external resources
// which defines test1 test2 and test3
// both should print `Hello World!`
// iframe scoped
bookmarklet([
"test1.js",
"test2.js",
"test3.js",
], function(){
console.log(`${test1}${test2}${test3}`)
}
)
// local scoped
bookmarklet([
"test1.js",
"test2.js",
"test3.js",
], function(){
console.log(`${test1}${test2}${test3}`)
},
local_scope
)
})()