È possibile sovrascrivere il metodo document.write. Quindi puoi bufferizzare le stringhe inviate a document.write ed emettere il buffer dove preferisci. Tuttavia, la modifica di uno script da sincrono a asincrono può causare errori se non gestita correttamente. Ecco un esempio:
sostituzione document.write semplificato
(function() {
// WARNING: This is just a simplified example
// to illustrate a problem.
// Do NOT use this code!
var buffer = [];
document.write = function(str) {
// Every time document.write is called push
// the data into buffer. document.write can
// be called from anywhere, so we also need
// a mechanism for multiple positions if
// that's needed.
buffer.push(str);
};
function flushBuffer() {
// Join everything in the buffer to one string and put
// inside the element we want the output.
var output = buffer.join('');
document.getElementById("ad-position-1").innerHTML = output;
}
// Inject the thid-party script dynamically and
// call flushBuffer when the script is loaded
// (and executed).
var script = document.createElement("script");
script.onload = flushBuffer;
script.src = "http://someadserver.com/example.js";
})();
Contenuto http://someadserver.com/example.js
var flashAdObject = "<object>...</object>";
document.write("<div id='example'></div>");
// Since we buffer the data the getElementById will fail
var example = document.getElementById("example");
example.innerHTML = flashAdObject; // ReferenceError: example is not defined
ho documentato i diversi problemi che ho incontrato durante la scrittura e usando il mio sostituzione document.write: https://github.com/gregersrygg/crapLoader/wiki/What-to-think-about-when-replacing-document.write
Ma il pericolo di utilizzare una sostituzione document.write sono tutti i problemi sconosciuti che possono sorgere. Alcuni non sono nemmeno in grado di andare in giro.
document.write("<scr"+"ipt src='http://someadserver.com/adLib.js'></scr"+"ipt>");
adLib.doSomething(); // ReferenceError: adLib is not defined
Per fortuna non ho incontrato il problema di cui sopra in natura, ma che non garantisce che non accadrà;)
Ancora voglia di provarlo? Prova crapLoader (mio) o writeCapture:
Dovresti anche dare un'occhiata allo friendly iframes. Fondamentalmente crea un iframe dello stesso dominio e carica tutto lì invece che nel tuo documento. Sfortunatamente non ho trovato alcuna buona libreria per gestire questo ancora.
è lo script di terze parti scaricato, quindi è possibile modificarlo?Penso che potrebbe essere una soluzione migliore di hacking 'document.write()' – peirix
Il mio esempio ha superato. Quello che volevo dire era: document.write ('<' + 'div'); document.write ('>' + 'Contenuto testo' + '<'); document.write ('\ div>') –
Posso modificarlo, ma oltre all'analisi completa di JS, esiste un modo per garantire che il codice modificato funzioni correttamente? –