Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WebBrowserControl:访问帧属性时发生UnauthorizedAccessException_C#_.net_Vb.net - Fatal编程技术网

C# WebBrowserControl:访问帧属性时发生UnauthorizedAccessException

C# WebBrowserControl:访问帧属性时发生UnauthorizedAccessException,c#,.net,vb.net,C#,.net,Vb.net,我使用默认的WebBrowser控件用C#编写了一个非常小的网站机器人。事实上,几乎所有的东西都按照它应该的方式工作,但我似乎在自动化的最后一步遇到了问题 该网站是使用几个iFrame构建的。这没什么大不了的,因为我只是使用 webBrowser1.Document.Window.Frames[0].Document.GetElementById("element").InvokeMember("click"); 但是,当IFRAME的源托管在与实际网站不同的域上时,不起作用。当我在互联网上搜

我使用默认的WebBrowser控件用C#编写了一个非常小的网站机器人。事实上,几乎所有的东西都按照它应该的方式工作,但我似乎在自动化的最后一步遇到了问题

该网站是使用几个iFrame构建的。这没什么大不了的,因为我只是使用

webBrowser1.Document.Window.Frames[0].Document.GetElementById("element").InvokeMember("click");
但是,当IFRAME的源托管在与实际网站不同的域上时,不起作用。当我在互联网上搜索我的问题的答案时,我偶然发现了一篇MSDN文章,其中提到了这个特定的问题,他们提到了防止跨站点脚本的安全措施,这可能是这个错误的原因

我真的找不到禁用此功能的方法,所以我继续前进,决定重新编码所有内容,以使用geckofx-12,而不是默认的(基于IE的)web浏览器控件,但我遇到了类似的问题

我的问题是:我有没有办法绕过这种恼人的行为?我并不关心安全问题,也不关心是否使用geckofx或默认的web浏览器控件,我只想通过编程方式访问托管在不同域上的站点元素,而不会遇到未经授权的DaccessException

我很想从那里的大师那里得到建议。

我没有尝试过,但显然很有效

使用geckofx 12,这似乎可以由nsIDOMHTMLDocument.SetDomainAttribute完成(GeckoDocument.Domain没有setter,但您可以轻松添加它)


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

您无法访问来自不同域的框架。这是一个安全特性。这里有一个小技巧:

 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);
}

我稍微更新了Daniel Bogdan发布的hack,以使用扩展方法,并提供了一种无需进入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的引用。您可以在此处找到相关说明:

不幸的是,我在尝试使用此方法时遇到了COM异常。然而,通过使用webBrowser1.Document.GetElementsByTagName(“iframe”)获取iframe并通过((Gecko.DOM.GeckoIFrameElement)frames[0]).ContentDocument访问其内容文档,我的工作正常。不过,我把你的答案标记为解决方案,因为反正没有其他答案。什么是IWebBrowser2?如果我能多次投票支持你,我会这么做的。工作得很好。@Kiquenet显然它来自SHDocVw:我已经添加了对dll的引用,但在SHDocVw名称空间中仍然没有IHTMLDocument2