【问题标题】:Objective-C: Grab title of web page from WebViewObjective-C:从 WebView 中获取网页的标题
【发布时间】:2013-12-08 18:06:07
【问题描述】:

我正在尝试检索网页的标题并将其显示在 NSWindows 标题中。这个应用程序是基于文档的,我没有在带有 AppDelegate 的独立应用程序中尝试过任何东西。我将如何继续检索标题并将其显示在窗口中?

更新:这是我的代码(注意:还不能正常工作)

TitleWindow.h

#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
@interface TitleWindow : NSWindow <NSApplicationDelegate> {

}

@property

(retain, nonatomic) IBOutlet NSWindow *displayTitle;

@end

TitleWindow.m

#import "TitleWindow.h"
#import <WebKit/WebKit.h>

@implementation TitleWindow


- (void)displayTitle:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame
{
    if (frame == [sender mainFrame]){
        [[sender window] setTitle:title];
    }
}

@end

【问题讨论】:

  • 与 Xcode 无关。
  • 另外,试试[webView stringByEvaluatingJavaScriptFromString: @"return document.title.toString();"];
  • @H2CO3 有点像这样? - (NSString *)windowNibName { // 重写返回文档的 nib 文件名 // 如果你需要使用 NSWindowController 的子类或者你的文档支持多个 NSWindowControllers,你应该删除这个方法并重写 -makeWindowControllers。 [webView stringByEvaluatingJavaScriptFromString:@"return document.title.toString();"]; }
  • @H2CO3 cmets 不允许我在语法视图中放置代码...所以我不知道该告诉你什么哈哈
  • 用反引号括起来,like this。但无论如何,大量代码并不适合 cmets。你不需要任何声明,我知道你正在尝试制作一个单独的方法。你也不需要为我复制 Xcode 无用的评论。

标签: objective-c macos url webview


【解决方案1】:

获取 NSWebViews 页面标题。

你用的是 mainFrameTitle

NSString * pageTitleString =[_webView mainFrameTitle];
    NSLog(@"%@" , pageTitleString);

Read the Docs

示例 2。

WebFrameLoadDelegate_Protocol

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)webFrame{

    [_window setTitle:[_webView mainFrameTitle]];

    }

更新 2

我之前还没有真正构建过基于文档的应用程序。所以设置一个显示网络视图很有趣:-P。

这让我认为问题有两个方面。


我发布的第一件事只是将示例2代码添加到document.m中是不够的。

webview 需要一个委托。

对我有用但可能不是(可能不是)正确的方法是在 Document.xib 中选择 web 视图。

顶部的 Connections Inspector 向您显示 frameLoadDelegate

我通过将其拖到 Place holder 窗格中的 file's Owner 将其连接到 file's Owner

这行得通。

每次我从文档中更改网页时,标题都会随之更改。


要注意的第二点是我认为设置文档标题的真正方法是:

[self setDisplayName:@"a title"];

在设置时有效:

- (void)windowControllerDidLoadNib:(NSWindowController *)aController

{
    [super windowControllerDidLoadNib:aController];


    // Add any code here that needs to be executed once the windowController has loaded the document's window.

 NSURLRequest* request = [NSURLRequest requestWithURL:_theUrls];
    [[_webView mainFrame] loadRequest:request];
     [self setDisplayName:@"a title"];
}

还有一个普通的字符串,但是如果我把它改成:

[self setDisplayName:[_webView mainFrameTitle]];

它不起作用,因为框架还没有加载,所以没有标题。

所以你会认为 [self setDisplayName:[_webView mainFrameTitle]];将在 WebFrameLoadDelegate 中工作。不,不是的。我不知道为什么。

所以现在你可能想要使用示例 2 中的代码。

【讨论】:

  • 好的,亲爱的。我用到目前为止的内容更新了我的原始帖子。我开始明白我需要什么的要点,但我有点迷失了。
  • 它仍然没有显示。代码编译完美。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 2011-01-23
  • 1970-01-01
相关资源
最近更新 更多