This is not even a direct answer because it does not involve a callback native, however, I can think that a solution would be the creation of a Loader capable of dynamically loading and processing page code, just like PHP does, for example.
The Loader would be an interpreter written in Javascript able to load a source code, starting reading in "html mode". When finding a tag <script>
, it would execute the respective code, depending on the language. In the case of Javascript, it could delegate to the browser itself.
Anyway, adding some restrictions to the way the page is loaded, in theory it seems possible.
Update: running Python along with Javascript in the browser
Based on the excellent find of @bfavaretto, the MutationObserver
, created a small project to run Python side-by-side with Javascript a page.
First I lowered the Brython, a Python 3 implementation in Javascript for running in the browser.
Then I set up a class based on the @bfavaretto code.
pyscript.js
//inicializa brython
brython();
// Cria objeto que vai monitorar alterações no DOM
function criaObserver(el) {
var observer = new MutationObserver(function(mutations) {
// Loop sobre as mutações detectadas
mutations.forEach(function(mutation) {
// Inserção de nós aparecem em addedNodes
var node = mutation.addedNodes[0];
// Achou um script
if(node && node.tagName === 'SCRIPT' && node.type === 'text/pyscript') {
console.log('encontrado pyscript')
var $src;
if(node.src!=='') {
// get source code by an Ajax call
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
var $xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
var $xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
$xmlhttp.open('GET',node.src,false)
$xmlhttp.send()
if($xmlhttp.readyState===4 && $xmlhttp.status===200){
$src = $xmlhttp.responseText
}
if ($src === undefined) { // houston, we have a problem!!!
console.log('erro ao carregar script')
return;
}
} else {
$src = node.textContent || node.innerText;
}
// ver https://bitbucket.org/olemis/brython/src/bafb482fb6ad42d6ffd2123905627148e339b5ce/src/py2js.js?at=default
// Passa o código para ser interpretado
__BRYTHON__.$py_module_path['__main__'] = window.location.href;
var $root=__BRYTHON__.py2js($src,'__main__');
$src = $root.to_js();
// eval in global scope
if (window.execScript) {
window.execScript($src);
return;
}
var fn = function() {
window.eval.call(window,$src);
};
fn();
}
});
});
// Inicia o observer, configurando-o para monitorar inserções de nós em qualquer nível
observer.observe(el, { childList: true, subtree: true })
return observer;
}
var observer = criaObserver(document);
Finally, I was able to successfully execute the code from the page below:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Python Test</title>
<script type="text/javascript" src="brython.js"></script>
<script type="text/javascript" src="pyscript.js"></script>
<script type="text/javascript">
var variavel = 1;
</script>
<script type="text/pyscript">
print('teste de print!')
print(variavel)
</script>
</head>
<body>
<div id="content">Conteúdo</div>
</body>
<script type="text/pyscript">
from _browser import doc, alert
alert('Valor da variável: ' + str(variavel))
lista = ['itens', 'da', 'lista']
doc['content'].text = 'Conteúdo colocado com python: ' + ' '.join(lista)
</script>
<script type="text/pyscript" src="teste.js"></script>
</html>
Note that there is the inclusion of an external file (teste.js
), containing the following python code:
d = { '11': 'um', '22': 'dois' }
for i in d:
print(i)
On the one hand, there is a limitation of this solution, derived from a limitation of Brython: Javascript code cannot access objects created within a Python chunk.
However, as seen in the example, doing the reverse is simple and straightforward, that is, the Python code has full access to Javascript code.
Dude, that’s a cool question! I don’t think I can answer, but I’ve had some questions here. If you use the tag "script" will not give confusion in the browser? You may need to create your own tag and access elements of it via DOM to interpret. Have tried something along these lines?
– Luiz Vieira
Oops. I just saw in your question that they are ignored by the browser. True. Sorry. :)
– Luiz Vieira
@Luiz Empirically I noticed that if I use one
type
which does not exist, the<script>
turns into a noop. But I don’t know how true it is. About creating a new tag, it will fall into the same problems I mentioned, won’t it? My goal is to have this operation as transparent as possible– Guilherme Bernal
Yes. The question is the order, mainly the intercalation with Javascript.
– Luiz Vieira
@Guilhermebernal answered there. If that’s more or less what you want, I add code that implements it for you. I’m just not going to make a whole interpreter of language because then it’s already forcing friendship. By the way, congratulations on the question. Vai +1 Fav
– Emerson Rocha
Someone has tried something very similar to what you want to do. See the article below: http://james.padolsey.com/javascript/custom-javascript-with-parsescripts/
– Leonel Sanches da Silva
+1 for the interesting question.
– user622