can I update the title bar?

2020-04-21 08:46发布

In a previous question I asked about updating a menu bar. BalusC told me that I need to add the form containing the menu bar.

I would like to extend that question to ask if I can update the text in the title. A template is being used and I fill in the value using

    <ui:define name="AreaTitle">
        #{viewBacking.current.firstName}  #{viewBacking.current.surName}
    </ui:define>

The template has

<h:head>
<title><ui:insert name="AreaTitle">Master template</ui:insert></title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</h:head>

It seems strange to define a form in the header so none is defined. I put a break point in the viewBacking.current so I can see when it uses it. Even if I hit the refresh to redisplay the form, it won't hit the break point again. Only when I go to a different page with different content does it hit the break point again. The for the refresh is

public void refreshForm() {
    RequestContext context = RequestContext.getCurrentInstance(); 
    context.update("menuForm:masterMenuBar");
    context.update("AreaTitle");
}

This shows the previous solution which BalusC gave me on the masterMenuBar. It could well be that I can't do what I'm asking to do, but I'd like confirmation if that is the case.

Thanks, Ilan

1条回答
够拽才男人
2楼-- · 2020-04-21 09:03

You can't update the title by JSF ajax update simply because <title> is not a JSF component. You also can't put HTML or JSF components in <title>, this is illegal HTML syntax.

Your best bet is to use JavaScript instead to update the title by assigning it to the document.title. You can use RequestContext#execute() for this.

String fullName = current.getFirstName() + " " + current.getSurName();
context.execute("document.title='" + fullName + "'");

Since this seems to be user-controlled data, I would use StringEscapeUtils#escapeJavaScript() to escape it in order to prevent potential XSS attack holes.

String fullName = current.getFirstName() + " " + current.getSurName();
context.execute("document.title='" + StringEscapeUtils.escapeJavaScript(fullName) + "'");

An alternative is to use OmniFaces <o:onloadScript>.

<o:onloadScript>document.title='#{of:escapeJS(viewBacking.current.firstName)} #{of:escapeJS(viewBacking.current.surName)}'</o:onloadScript>

This will be re-executed on every ajax request.

查看更多
登录 后发表回答