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

问题描述 投票:2回答:3

我试图懒惰加载一些广告服务器代码...

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

<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广告调用的结果替换span。

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

javascript document.write adserver
3个回答
6
投票

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

document.old_write = document.write;

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

见这里:http://www.jsfiddle.net/N9hXy/


1
投票
document.write = function(str) {
    window.buf += str;
}

0
投票

必须在某处调用do_ad(pos)函数。为什么不显示广告的位置?

<div class="ad">
    <script>do_ad("pos_1");</script>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.