在加载页面后添加的脚本中如何处理document.write? [英] How to deal with document.write in a script that's added after a page has loaded?

查看:118
本文介绍了在加载页面后添加的脚本中如何处理document.write?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正处于需要动态添加广告脚本标签的情况。

I'm in a situation where I need to add an advertisement script tag dynamically.

广告本身只是一个简单的脚本标签,src属性指向广告服务器。然后运行的实际代码是一个两步的磨合:

The ad itself is just a simple script tag with the src attribute pointing to the ad server. The actual code which is then ran is a 2-step ordeal:

首先,有一个document.write(),像这样:

First, there is a document.write(), like so:

document.write("<iframe id='lctopti2017041855' src='about:blank' style='visibility: hidden;' onload=\"this.style.visibility='visible';\" style='border: 0px; overflow-x: hidden;overflow-y: hidden; width: 100px; height: 400px;' width='100' height='400' scrolling='no' frameborder='0' allowtransparency='true'></iframe>");

接下来,有一个:

document.getElementById('lctopti2017041855').src = 'http://www.reallylongurl.com/blah.php?whatever=whatever'

现在,似乎在页面正在加载时运行document.write()是正确的;但是我发现如果我使用相同的初始标签,并将其弹出($#somediv')。prepend(),例如,它将覆盖整个页面。

Now, it seems that running document.write() as the page is loading is fine; but I've discovered that if I took the same initial tag and popped it inside of $('#somediv').prepend(), for instance, it would overwrite the entire page.

有什么办法来处理吗? iframe ID和随后的广告网址始终是动态的,并且在初始脚本标签从广告服务器请求JavaScript时生成。如果初始脚本标签具有我需要的所有信息,我可以使用$('#anywhere')。prepend()或其他东西简单地切换document.write。我如何解决这个问题,简单的说是把初始脚本加载的结果拖下来,然后使用结果?

Is there any way to deal with this? The iframe id and the subsequent ad urls are always dynamic, and generated when the initial script tag requests the javascript from the ad server. If the initial script tag had all the information I needed, I could simply switch out document.write with $('#anywhere').prepend() or something. How can I solve this, short of literally scraping the results of the initial script load and then working with the result?

有没有办法阻止document.write()

Is there a way to stop document.write() from overwriting the page but instead only writing where it was called?

推荐答案

这是我在

var oldWrite = document.write;
var wHtml="";
document.write=function(str) {
  wHtml+=str;
}
// load adcode
$('#somediv').prepend(wHtml);
// optionally reset
document.write = oldWrite;

如果广告代码使用document.write加载脚本,则可能会失败。
在这种情况下,使用iFrame,因为它将包含他们可以做的所有废话

This may fail if the adcode loads a script using document.write too. In that case use an iFrame since it will contain all the crap they can do

这篇关于在加载页面后添加的脚本中如何处理document.write?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆