有没有办法拦截`document.write`?

发布于 2024-10-12 18:08:00 字数 726 浏览 10 评论 0原文

我正在尝试延迟加载一些广告服务器代码...

在页面上,我现在有这个:

<div class="ad">
    <span>pos_1</span>
</div>

然后我浏览并拉出应该在页面上的所有广告,调用他们的 javascript 包含文件,它给了我这个可爱的混乱:

function do_ad(pos){
    switch(pos){
        case 'pos_1':
            document.write('first ad text');
            document.write('first ad more text');
            //and so on for many many lines
            break;
        case 'pos_2':
            document.write('second ad text');
            document.write('second ad more text');
            //and so on for many many lines
            break;
    }
}

然后我想用 document.write 广告调用的结果替换跨度。

有没有办法让它返回已写入页面的字符串?

I am trying to lazy load some adserver code...

On the page I have this at the moment:

<div class="ad">
    <span>pos_1</span>
</div>

I then go through and pull out all of the ads that should be on the page, call their javascript include file and it gives me this lovely mess:

function do_ad(pos){
    switch(pos){
        case 'pos_1':
            document.write('first ad text');
            document.write('first ad more text');
            //and so on for many many lines
            break;
        case 'pos_2':
            document.write('second ad text');
            document.write('second ad more text');
            //and so on for many many lines
            break;
    }
}

I then want to replace the span with the results of the document.write ad call.

Is there a way to get it to return the string that would have been written to the page?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

趁年轻赶紧闹 2024-10-19 18:08:00

我不明白为什么你不能覆盖 document.write 函数:

document.old_write = document.write;

document.write = function (str) {
    // lalala
};

请参见此处:http://www.jsfiddle.net/N9hXy/

I don't see why you can't overwrite the document.write function:

document.old_write = document.write;

document.write = function (str) {
    // lalala
};

See here: http://www.jsfiddle.net/N9hXy/

〆凄凉。 2024-10-19 18:08:00
document.write = function(str) {
    window.buf += str;
}
document.write = function(str) {
    window.buf += str;
}
命硬 2024-10-19 18:08:00

必须在某处调用 do_ad(pos) 函数。为什么不应该在广告展示的地方呢?

<div class="ad">
    <script>do_ad("pos_1");</script>
</div>

The do_ad(pos) function must be called somewhere. Why not where the ad should be displayed?

<div class="ad">
    <script>do_ad("pos_1");</script>
</div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文