WebBrowserControl:访问Frame属性时出现UnauthorizedAccessException

6
我使用默认的WebBrowser控件用C#编写了一个非常小的网站机器人。实际上,几乎所有的功能都按照预期工作,但我好像在自动化的最后一步遇到了问题。
该网站使用了多个iframe构建。这并不是什么大问题,因为我只需访问这些框架及其元素就可以了。
webBrowser1.Document.Window.Frames[0].Document.GetElementById("element").InvokeMember("click");

然而,当IFRAME的源被托管在与实际网站不同的域上时,这种方法就无法工作了。当我在互联网上搜索答案时,我偶然发现了一篇MSDN文章提到了这个特定的问题,并且他们提到了针对跨站点脚本攻击的安全措施可能是这个错误的原因。
我找不到禁用此功能的方法,所以我决定重新编写一切,以使其适用于geckofx-12而不是默认(基于IE的)Web浏览器控件,但我遇到了类似的问题... 我的问题是:有没有办法绕过这个烦人的行为? 我并不真的关心安全问题或者是否使用geckofx或默认的Web浏览器控件,我只想以编程方式访问托管在不同域上的站点的元素,而不会遇到UnauthorizedAccessException。
我很想从专家那里得到建议。
3个回答

8

您无法访问来自不同域的框架,这是一项安全功能。但有一个小技巧可以解决:

 public class CrossFrameIE
{
    // Returns null in case of failure.
    public static IHTMLDocument2 GetDocumentFromWindow(IHTMLWindow2 htmlWindow)
    {
        if (htmlWindow == null)
        {
            return null;
        }

        // First try the usual way to get the document.
        try
        {
            IHTMLDocument2 doc = htmlWindow.document;                

            return doc;
        }
        catch (COMException comEx)
        {
            // I think COMException won't be ever fired but just to be sure ...
            if (comEx.ErrorCode != E_ACCESSDENIED)
            {
                return null;
            }
        }
        catch (System.UnauthorizedAccessException)
        {
        }
        catch
        {
            // Any other error.
            return null;
        }

        // At this point the error was E_ACCESSDENIED because the frame contains a document from another domain.
        // IE tries to prevent a cross frame scripting security issue.
        try
        {
            // Convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider.
            IServiceProvider sp = (IServiceProvider)htmlWindow;

            // Use IServiceProvider.QueryService to get IWebBrowser2 object.
            Object brws = null;
            sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out brws);

            // Get the document from IWebBrowser2.
            IWebBrowser2 browser = (IWebBrowser2)(brws);

            return (IHTMLDocument2)browser.Document;
        }
        catch
        {
        }

        return null;
    }

    private const int E_ACCESSDENIED = unchecked((int)0x80070005L);
    private static Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
    private static Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E");
}

// This is the COM IServiceProvider interface, not System.IServiceProvider .Net interface!
[ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider
{
    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);
}

1
什么是 IWebBrowser2 - Kiquenet
如果我可以给你点赞超过一次,我一定会这么做。它完美地运行。 - DoronG
@Kiquenet,显然它来自SHDocVw:https://dev59.com/questions/A2Ei5IYBdhLWcg3w6PzZ - Drew Delano
我已经将dll添加到引用中,但SHDocVw命名空间仍然没有IHTMLDocument2。 - Nikolai Frolov

6

我稍微改进了Daniel Bogdan发布的黑客技巧,使用扩展方法并提供了一种不必进入mshtml命名空间即可调用它的方式:

using mshtml;
using SHDocVw;
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TradeAutomation
{
    public static class CrossFrameIE
    {
        private static FieldInfo ShimManager = typeof(HtmlWindow).GetField("shimManager", BindingFlags.NonPublic | BindingFlags.Instance);
        private static ConstructorInfo HtmlDocumentCtor = typeof(HtmlDocument).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];

        public static HtmlDocument GetDocument(this HtmlWindow window)
        {
            var rawDocument = (window.DomWindow as IHTMLWindow2).GetDocumentFromWindow();

            var shimManager = ShimManager.GetValue(window);

            var htmlDocument = HtmlDocumentCtor
                .Invoke(new[] { shimManager, rawDocument }) as HtmlDocument;

            return htmlDocument;
        }


        // Returns null in case of failure.
        public static IHTMLDocument2 GetDocumentFromWindow(this IHTMLWindow2 htmlWindow)
        {
            if (htmlWindow == null)
            {
                return null;
            }

            // First try the usual way to get the document.
            try
            {
                IHTMLDocument2 doc = htmlWindow.document;

                return doc;
            }
            catch (COMException comEx)
            {
                // I think COMException won't be ever fired but just to be sure ...
                if (comEx.ErrorCode != E_ACCESSDENIED)
                {
                    return null;
                }
            }
            catch (System.UnauthorizedAccessException)
            {
            }
            catch
            {
                // Any other error.
                return null;
            }

            // At this point the error was E_ACCESSDENIED because the frame contains a document from another domain.
            // IE tries to prevent a cross frame scripting security issue.
            try
            {
                // Convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider.
                IServiceProvider sp = (IServiceProvider)htmlWindow;

                // Use IServiceProvider.QueryService to get IWebBrowser2 object.
                Object brws = null;
                sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out brws);

                // Get the document from IWebBrowser2.
                IWebBrowser2 browser = (IWebBrowser2)(brws);

                return (IHTMLDocument2)browser.Document;
            }
            catch
            {
            }

            return null;
        }

        private const int E_ACCESSDENIED = unchecked((int)0x80070005L);
        private static Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
        private static Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E");
    }

    // This is the COM IServiceProvider interface, not System.IServiceProvider .Net interface!
    [ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"),
    InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IServiceProvider
    {
        [return: MarshalAs(UnmanagedType.I4)]
        [PreserveSig]
        int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);
    }
}

使用方法:

webBrowser1.Document.Window.Frames["main"].GetDocument();

如我之前的评论所述,您还需要添加对SHDocVw的引用。您可以在此处找到相关方向:使用Visual C# 2010 Express在C#项目中添加“SHDocVw”引用


2

我没有尝试过,但是通过更改文档域 似乎可以实现。

在使用geckofx 12时,这似乎可以通过nsIDOMHTMLDocument.SetDomainAttribute来完成(GeckoDocument.Domain没有设置器,但您可以轻松添加它)

IE. 如果您更改文档的域以匹配子框架,则可能可以访问它。


2
很不幸,在尝试使用该方法时,我遇到了COM异常。但是,通过使用webBrowser1.Document.GetElementsByTagName("iframe")获取iframes并通过((Gecko.DOM.GeckoIFrameElement)frames[0]).ContentDocument访问它们的内容文档,我成功地解决了问题。虽然没有其他答案,但我仍将您的答案标记为解决方案。 - beta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接