如何将HTML元素添加到Cocoa Webview

时间:2012-03-01 18:36:58

标签: cocoa dom webkit

我一直在尝试将HTML内容添加到网络视图中,但似乎无法获得任何结果。 Apple文档非常稀疏,而few示例中我发现online,我似乎无法使其中的任何一个工作。据我所知,这是它应该如何运作,但不是。

首先,我有一个非常简单的HTML文档,我加载到webview中。我试图将一些HTML内容添加到#container div

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>HTML TEST</title>

        <style type="text/css">       
            .test {
                display: block;
                border: #000 1px solid;
                width: 100px;
                height: 100px;
                background-color: #0F0;

            }            
         </style>
    </head>
    <body>   
        <p>hello world</p>
        <div id="container"></div>
    </body>
</html>

WebView位于自定义视图中。标题非常直接。

// NodeTest.h
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>

@interface NodeTest : NSView
@property (nonatomic, retain) IBOutlet WebView *webview;
@end

因此,在awakefromnib中,我加载了基本的html文档,尝试获取容器div并在其中插入一个新的HTML元素,类名为&#34; test&#34;。其中,根据HTML文件应该有黑色边框,绿色填充应该是100x100px。

#import "NodeTest.h"

@implementation NodeTest

@synthesize webview;

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (void) awakeFromNib {
    // Load the HTML document into the webview
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"TestDocument" ofType:@"html"]];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    [[webview mainFrame] loadRequest:req];

    [webview setEditable:YES];

    DOMDocument *domDoc = [[webview mainFrame] DOMDocument];

    // Get the container div. I've tried this with and without '#'
    DOMHTMLElement *container = (DOMHTMLElement *)[domDoc getElementById:@"container"];

    // Create a new HTML element
    DOMHTMLElement *myDiv = (DOMHTMLElement *)[domDoc createElement:@"div"];
    [myDiv setInnerHTML:@"<p>Boo!</p>"];
    [myDiv setClassName:@"test"];

    // Add the element to the container div
    [container appendChild:myDiv];

    [webview setNeedsDisplay:YES];

}

- (void)drawRect:(NSRect)dirtyRect
{
    // Drawing code here.
}

@end

将HTML内容加载到WebView中很好。它就在那里。但我不能为我的生活弄清楚如何添加新的HTML元素。如果有人有任何指示,我很乐意听到他们。这让我很生气。

1 个答案:

答案 0 :(得分:2)

WebKit异步加载请求,因此您需要在调用-[WebFrame loadRequest:]之后旋转运行循环,直到加载完成,然后才尝试访问DOM。旋转运行循环的常用方法是从-awakeFromNib返回,但如果需要,您还可以使用NSRunLoop API旋转嵌套的运行循环。找出加载完成时间的标准方法是给WebView一个WebFrameLoadDelegate并等待其-webView:didFinishLoadForFrame:方法被调用。 (如果要加载包含子帧的资源,则需要等到主帧传递给该方法。)

加载完成后,您列出的访问-DOMDocument等的代码应该可以正常工作。