简体   繁体   English

如何定期更改页面标题并打开/关闭更改?

[英]How can I change Page Title periodically and switch the change on/off?

I want to change the title of my page periodically, ie add a (*) in front of the current page title and remove it after a couple of seconds. 我想定期更改页面标题,即在当前页面标题之前添加(*),并在几秒钟后将其删除。 I want to turn this title change on and off in code. 我想在代码中打开和关闭此标题更改。

I get and set the page title from: 我从以下位置获取并设置页面标题:

    public static native void setPageTitle(String title) /*-{
    $doc.title = title;
    }-*/;


public static native String getPageTitle() /*-{
    return $doc.title;
}-*/;

But how should I write a function that will change the page title every 300 miliseconds while adding and removing a prefix? 但是,我应该如何编写一个函数,在添加和删除前缀时每300毫秒更改页面标题呢?

What I tried was: 我试过的是:

private void changePageTitle(final String prefix) {

    new Timer() {
        @Override
        public void run() {
            String pageTitle =getPageTitle();

            if (pageTitle.startsWith(prefix)) {
                    pageTitle = pageTitle.substring(prefix.length());
                }
                else {
                    pageTitle = pageTitle + prefix;
                }
            setPageTitle(pageTitle);

        }
        }
    }.schedule(300);
}

This does not work. 这是行不通的。 And I do not know how to switch the process on and off? 而且我不知道如何打开和关闭该过程?

The Effect should be like in Facebook. 效果应类似于Facebook。 When a new message arrive and you are not on the Facebook browser tab, then the tab shows a notification which is blinking. 当收到新消息且您不在Facebook浏览器选项卡上时,该选项卡显示闪烁的通知。

You have to change schedule(300) by scheduleRepeating(300) . 你必须改变schedule(300)scheduleRepeating(300)

You should use just one instance of Timer or save the last timer to cancel it before creating a new one. 您应该只使用一个Timer实例,或者保存最后一个计时器以将其取消,然后再创建一个实例。

BTW: you dont need to write any JSNI to access the window title, just use Window.getTitle() and Window.setTitle(String) 顺便说一句:您不需要编写任何JSNI来访问窗口标题,只需使用Window.getTitle()Window.getTitle() Window.setTitle(String)

EDITED: 编辑:

This should work: 这应该工作:

// create just an instance of the timer
final MyUpdateTitleTimer mytimer = new MyUpdateTitleTimer();
// To Start the updater
mytimer.setPrefix("> ");
// To Stop set the prefix to null
mytimer.setPrefix(null);


class MyUpdateTitleTimer extends Timer {
  private String prefix;
  private String title;
  private boolean b;

  public void run() {
    String s = (b = !b) ? prefix + title : title;
    Window.setTitle(s);
  }

  public void setPrefix(String prefix) {
    if (title != null) {
      Window.setTitle(title);
    }
    this.prefix = prefix;
    if (prefix == null) {
      cancel();
    } else {
      title = Window.getTitle();
      scheduleRepeating(300);
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM