Note: Advice in this article will only work for JxBrowser 6. See the corresponding article for JxBrowser 7 here.(注意:本文中的建议仅适用于JxBrowser6,JxBrowser7相应文章请点击这里。)


Using Network API you can control all incoming and outgoing cookies. You can enable/disable saving/sending cookies. Using the NetworkDelegate.onCanSetCookies(String url, List<Cookie> cookies) method you can decide whether cookies should be saved or not. To disable sending some cookies to a web server you can use the NetworkDelegate.onCanGetCookies(String url, List<Cookie> cookies) method. (使用网络API,您可以控制所有传入和传出的Cookie。您可以启用/禁用保存/发送cookie。使用NetworkDelegate.onCanSetCookies(String url,List cookie)方法,您可以决定是否保存cookie。若要禁用向Web服务器发送一些cookie,可以使用NetworkDelegate.onCanGetCookies(String url,List cookie)方法。)

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.Cookie;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultNetworkDelegate;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * The sample demonstrates how to suppress/filter incoming and outgoing cookies.
 */
public class CookieFilterSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView browserView = new BrowserView(browser);

        // Suppress/filter all incoming and outgoing cookies.
        browser.getContext().getNetworkService().setNetworkDelegate(new DefaultNetworkDelegate() {
            @Override
            public boolean onCanSetCookies(String url, List<Cookie> cookies) {
                return false;
            }

            @Override
            public boolean onCanGetCookies(String url, List<Cookie> cookies) {
                return false;
            }
        });

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(browserView, BorderLayout.CENTER);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}