使用观察者,得到含字符集的第一次应答。
1)AddObserver
org.mozilla.browser.IMozillaWindow#onAttachBrowser(ChromeAdapter chromeAdapter, ChromeAdapter parentChromeAdapter)
// zzf private void addCharsetObserver() { // 新页面,重置。 charset = null; obs = (nsIObserverService) Mozilla .getInstance() .getServiceManager() .getServiceByContractID("@mozilla.org/observer-service;1", nsIObserverService.NS_IOBSERVERSERVICE_IID); charsetObserver = new nsIObserver() { @Override public nsISupports queryInterface(String uuid) { return Mozilla.queryInterface(this, uuid); } @Override public void observe(nsISupports subject, String topic, String data) { if (charset == null && charsetObserverName.equals(topic)) { nsIHttpChannel httpChannel = (nsIHttpChannel) subject .queryInterface(nsIHttpChannel.NS_IHTTPCHANNEL_IID); httpChannel .visitResponseHeaders(new nsIHttpHeaderVisitor() { public void visitHeader(String header, String value) { // header=[Content-Type] value=[text/html; // charset=GB2312] if (charset == null && "content-type".equals(header .toLowerCase())) { int eq = value.lastIndexOf('='); if (eq != -1 && value.length() > eq + 1) { charset = value.substring(eq + 1); // System.out.println("设置字符集="+ // charset); } } } public nsISupports queryInterface(String uuid) { return null; } }); } } }; obs.addObserver(charsetObserver, charsetObserverName, false); }
2)RemoveObserver
org.mozilla.browser.IMozillaWindow#onDetachBrowser
private void removeCharsetObserver() { obs.removeObserver(charsetObserver, charsetObserverName); }
3)设置字符集
org.mozilla.browser.IMozillaWindow#onAttachBrowse
ChromeAdapter->nsIWebBrowser->nsIInterfaceRequestor->nsIDocShell#setDocumentCharsetInfo
docShell.setDocumentCharsetInfo(new nsIDocumentCharsetInfo() { nsIAtom atom = new nsIAtom() { @Override public nsISupports queryInterface(String uuid) { return Mozilla.queryInterface(this, uuid); } @Override public boolean _equals(String arg0) { return true; } @Override public boolean equalsUTF8(String arg0) { return true; } @Override public String toUTF8String() { // 会调用到此方法 return charset == null ? "UTF-8" : charset; } }; @Override public nsISupports queryInterface(String uuid) { return Mozilla.queryInterface(this, uuid); } @Override public nsIAtom getForcedCharset() { // 会调用到此方法 return atom; } @Override public boolean getForcedDetector() { return true; } @Override public nsIAtom getParentCharset() { return null; } @Override public int getParentCharsetSource() { return 0; } @Override public void setForcedCharset(nsIAtom arg0) { // 会调用到此方法,参数arg0==null(不管页面是否设置了charset都是null) // System.out.println(arg0); } @Override public void setForcedDetector(boolean arg0) { // System.out.println(arg0); } @Override public void setParentCharset(nsIAtom arg0) { // System.out.println(arg0); } @Override public void setParentCharsetSource(int arg0) { // System.out.println(arg0); } });
Gecko可深入应用于java embbed,当看到webkit喧哗时似有w无g的感觉,巨不爽。