在使用webbrowser的过程中,跨域是个头痛问题,从顶层到内层还能找到方法,从内层想要跨域到顶层在同域的情况下也很简单,如果不同域会提示:拒绝访问!应该是安全机制在作怪吧。问题总结如下图:

  以下内容均在不同域的前提下产生(同域的不用这么麻烦):

通过从顶层访问内层,我得到了inputIframe这个元素,如果想从inputIframe逐级向上推导,得到顶层(上一层)的Document,一般手段是行不通的,在网上找到一篇文章,不过没看懂:http://msdn.microsoft.com/en-us/library/ms537182(VS.85).aspx,不知道这几个接口怎么用,无奈之下,只有改变思维方式:既然能从顶层访问到内层,那么不一定需要从内层向上取Document,也可以从顶层向内层推导,如果取到的Document和内层的Documnet一样不就行了?

function TfrmSetTask.GetActiveElmPos(Doc: IHTMLDocument2;ELm:ihtmlelement): tpoint;
var
Element: IHTMLElement;
Frame: IHTMLFrameElement;
WB: IWebBrowser2;
HtmlDoc2: IHTMLDocument2;
begin
ELm.scrollIntoView(0);
(ELm as IHTMLElement3).setActive;

HtmlDoc2:=Doc;
Element := HtmlDoc2.activeElement;

Result:=Point(0,0);

while not ((Element.tagName=ELm.tagName) and (Element.sourceIndex=ELm.sourceIndex)) do
begin

Element := HtmlDoc2.activeElement;

Result.X:=Result.X+(Element as ihtmlelement2).getBoundingClientRect.left;
Result.y:=Result.y+(Element as ihtmlelement2).getBoundingClientRect.top;

if not Assigned(Element) then Break;
if Element.QueryInterface(IHTMLFrameElement, Frame) <> S_OK then Break;
if Frame.QueryInterface(IID_IWebBrowser2, WB) <> S_OK then Break;
if not Assigned(WB.Document) then Break;
if WB.Document.QueryInterface(IID_IHTMLDocument2, HtmlDoc2) <> S_OK then Break;

end;
Result.X:=Result.X+(Elm as ihtmlelement2).getBoundingClientRect.left;
Result.y:=Result.y+(Elm as ihtmlelement2).getBoundingClientRect.top;
end;

在上面的函数中,需要传入一个顶层的Doc和一个已知的内层htmlElment,就可以计算出内层htmlElment相对于Webbrowser控件的位置(注意:不是相对于顶层document的位置),把这个函数改下,也可以得到想要的Document.

   总结下:本文有取巧之嫌,如果有更好的方法希望能回复一下,谢谢。

posted on 2012-03-22 11:53  Bach  阅读(3042)  评论(0编辑  收藏  举报