Cordova inAppBrowser : Display Custom title
Cordova inAppBrowser在安卓端默认顶部栏显示是当前访问的URL,可以变更为自定义的内容或者读取当前网页的标题时行替换。
然而IOS并没有内容,需要自行添加,下面是代码片段示例
Android
插件找到文件InAppBrowser.java
,添以以下代码。
原理是利用原有显示的url,替换成自定义的内容。
InAppBrowser.java
// 125
private static final String TITLE_STATIC_TEXT = "titlestatictext";
// 126
private static final List customizableOptions = Arrays.asList(CLOSE_BUTTON_CAPTION, TOOLBAR_COLOR, NAVIGATION_COLOR, CLOSE_BUTTON_COLOR, FOOTER_COLOR,
TITLE_STATIC_TEXT);
// 727
String titleStaticTextSet = features.get(TITLE_STATIC_TEXT);
if (titleStaticTextSet != null) {
titleStaticText = titleStaticTextSet;
}
// 大约1460行
public void onPageFinished(WebView view, String url) {
// ...
view.clearFocus();
view.requestFocus();
// 在此处添加以下代码
// 设置为当前网页的标题
edittext.setText(inAppWebView.getTitle());
// 设置为前端js自定义的属性内容
edittext.setText(titleStaticText);
// 结束
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
// ...
}
如要居字字体和取消下划线,则需要在文件InAppBrowser.java
添加以下代码
// 大概在925行
// Edit Text Box
// ...
// edittext的最后面,在此处添加以下代码
edittext.setGravity(Gravity.CENTER_HORIZONTAL);
edittext.setBackgroundResource(android.R.color.transparent);
// ^
// Header Close/Done button
// ...
IOS
插件在IOS中,并没有显示内容,需要添加文本区域,下面是主要的代码片段
CDVInAppBrowserOptions.h
@property (nonatomic, copy) NSString* titlestatictext;
CDVInAppBrowserOptions.m
self.titlestatictext = nil;
CDVWKInAppBrowser.m
// 约895行
// <-- 开始增加代码
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 11.0f, self.view.frame.size.width, 21.0f)];
[titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];
[titleLabel setBackgroundColor:[UIColor clearColor]];
[titleLabel setTextColor:[UIColor colorWithRed:157.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0]];
[titleLabel setText:@""];
[titleLabel setTextColor:UIColor.whiteColor];
[titleLabel setTextAlignment:NSTextAlignmentCenter];
if (_browserOptions.titlestatictext) {
[titleLabel setText:_browserOptions.titlestatictext];
}
UIBarButtonItem *title = [[UIBarButtonItem alloc] initWithCustomView:titleLabel];
// -- > 结束增加代码
// 接着修改下面代码,将`flexibleSpaceButton`替换成`title`
// Filter out Navigation Buttons if user requests so
if (_browserOptions.hidenavigationbuttons) {
if (_browserOptions.lefttoright) {
[self.toolbar setItems:@[flexibleSpaceButton, self.closeButton]];
} else {
[self.toolbar setItems:@[self.closeButton, flexibleSpaceButton]];
}
} else if (_browserOptions.lefttoright) {
[self.toolbar setItems:@[self.backButton, fixedSpaceButton, self.forwardButton, title, self.closeButton]];
} else {
[self.toolbar setItems:@[self.closeButton, title, self.backButton, fixedSpaceButton, self.forwardButton]];
}