This is the first post I made a bookmarklet that works with code written in Python using Brython The second half is just code golf
http://qiita.com/ryo_grid/items/5e34220ed48f4580126d This was very helpful.
(Maybe) No
bookmarklet
javascript:
(function() {
var py = document.createElement('script');
py.type = 'text/python';
py.src = 'https://example/script.py';
document.body.appendChild(py);
var br = document.createElement('script');
br.src = 'https://example/brython.js';
br.onload = function() {
brython();
};
document.body.appendChild(br);
})();
/script.py
from browser import alert
alert("Hello World!")
The mechanism is simple, just before </ body>
<script type="text/python" src="https://example/script.py"></script>
<script src="https://example/brython.js"></script>
Is just adding
After loading brython.js
, callbrython ()
using the onload attribute to run the text / python
script in the page.
Brython uses Ajax to load any external scripts Therefore, there is a fatal problem that bookmarklets do not work except on the server page where the script is placed. So I solved it by adding ʻAccess-Control-Allow-Origin: *` to the HTTP header
It's a bookmarklet, so it should be shorter (?)
Also put the document in a variable
javascript:
(function(d,p,b) {
p = d.createElement('script');
p.type = 'text/python';
p.src = 'https://example/script.py';
d.body.appendChild(p);
b = d.createElement('script');
b.src = 'https://example/brython.js';
b.onload = function() {
brython();
};
d.body.appendChild(b);
})(document);
Call with ʻarguments.callee` because there is no function name (If you give a function name, a space will be inserted and it is inappropriate as a bookmarklet) Use ternary operator without if statement
javascript:
(function d(d,u,c,e) {
e = d.createElement('script');
e.src = u + (c ? 'brython.js' : 'script.py');
c ? (arguments.callee(d,u), e.onload = function() {
brython();
}) : (e.type = 'text/python');
d.body.appendChild(e);
})(document,'https://example/',1);
javascript:(function d(d,u,c,e) {e=d.createElement('script');e.src=u+(c?'brython.js':'script.py');c?(arguments.callee(d,u),e.onload=function(){brython();}):(e.type='text/python');d.body.appendChild(e);})(document,'https://example/',1);
330 characters => 235 characters I think it's still a long time, but my technology seems to be the limit
It's over, have a good Python life!
Recommended Posts