This is not a straightforward answer since it does not involve a native callback , but I can think of a solution that would be to create a loader dynamically page code, just like PHP does, for example.
loader would be an interpreter written in JavaScript capable of loading a source code, starting reading in "html mode". Upon finding a <script>
tag, it would start executing its code depending on the language. In the case of JavaScript, you could delegate to the browser itself.
Anyway, adding some restrictions to how the page loads, in theory seems to be possible.
Update: Running Python along with Javascript in Browser
Based on the great find of @bfavaretto , MutationObserver
, I created a small project to run Python side-by-side with a Javascript page.
First I downloaded Brython , a Python 3 implementation in Javascript for running in the browser.
Then I mounted 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 page code 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 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 Brython limitation: JavaScript code can not access objects created within a Python excerpt.
However, as seen in the example, doing the reverse is simple and straightforward, that is, the Python code has full access to Javascript code.