Overriding document.write within a specified scope?

。_饼干妹妹 提交于 2019-12-24 10:57:53

问题


I need to override document.write in order to render an ad that comes back wrapped in that function from google's doubleclick. Since the standard document.write replaces the page content entirely, i overrode it to append the contents of the ad to an existing element. However, I want to make sure that this override only occurs during the ad render and that any other document.writes that may be on the page are unaffected. Can this be scoped or accomplished via closure? I'm not very familiar with how that is done.

So far I have:

(function(){
function RenderAd(adURL,Element)
{
    document.write = function(adContent) {                         
        Element.append(adContent);
    }  
    $.getScript(adURL);
}
  RenderAd('http://ad.doubleclick.net/N4890/adj/za.za.home/main;pos=300top;tile=2;sid=Amazon;sz=300x250;ord=12247707435800953?',$('#HeaderDiv'));
}(document.write));

But when I call document.write('test'); afterwards, it is still using my version of document.write.


回答1:


document.write is scoped within an HTML document so if you change it, any subsequent call to it will also execute the overwritten version. You could try something like storing the original document.write function in a temp var, overwritting it and then replacing it after you've completed the function call, however since the call to document.write is through a callback and is async, and since you're probably loading multiple ads on a page this way, you can't predict when you should restore the original document.write.

What's typically done in a scenario where a service call returns HTML wrapped in a document.write() call is to load that in a separate iframe, which will have its own document object.

So if you can, create an iframe for each ad and load the returned data from your call to Google's doubleclick into the iframe. the document.write will create a buffer just for that iframe and won't affect the parent HTML.




回答2:


Use an iframe to place the ad. That way, you don't have to override the document.write. The ad would render on its own iframe and will not mess with the main page's document.write.

Another solution considered: 1. save original document.write in a variable 2. override document.write to your version 3. restore original document.write in $.getScript success callback.

But that would not work, as the callback is not fired after the script has executed.




回答3:


Welcome to try https://github.com/shenjunru/LazyWrite

It allows you to control the document.write().

Hope it can solve your problem. Any question is welcome.



来源:https://stackoverflow.com/questions/21141839/overriding-document-write-within-a-specified-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!