从java程序关闭Web浏览器对特定URL [英] Closing a Web Browser for a specific URL from the java program

查看:292
本文介绍了从java程序关闭Web浏览器对特定URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要关闭打开网页浏览器/标签浏览器从java程序特定的URL。
我可以使用桌面API从Java在Internet Explorer中打开URL。

I want to close an open web browser/browser tab for a specific URL from the java program. I am able to open the URL in internet explorer using the Desktop API from java.

下面是code片段来在IE中打开浏览器

Below is the code snippet to open the browser in IE

java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
desktop.browse(new java.net.URI("http://www.xyzz.com"));

现在当我再次运行程序我想,以确保没有已经存在的实例,其中上面的网址在浏览器中打开。如果是这样,将其关闭,并在新的选项卡或浏览器窗口再次打开它。这可能看起来有点古怪的要求。

Now When I run the program again I want to make sure that there is no already instance where the above URL is opened in the browser. If it is so, close it and open it again in a new TAB or Browser window. This may look little weird requirement.

我知道基本的做法应该得到关于这个问题,我们需要确定过程,并杀死它比再次调用上述code。

I know the basic approach should to get on to this issue is that, we need to identify the process and kill it and than again invoke the above code.

任何建议是值得欢迎的。

Any suggestion is welcome.

推荐答案

我怀疑有很多你可以与桌面做,因为你没有得到启动的过程中任何引用。

I doubt there is much you can do with Desktop since you don't get any reference to the launched process.

我已经在过去使用这种技术(Java 6中,其中桌面不存在前),因为它与过程的工作,你应该能够杀死它。

I have used this technique in the past (before Java 6 where Desktop did not exist) and since it works with Process, you should be able to kill it.

public static void openURL(String url) {
    StringBuilder sb = new StringBuilder();
    if (System.getProperty("os.name").indexOf("Windows")>-1) {
        String command = null;
        String urlLC = url.toLowerCase();
        if (urlLC.startsWith("https")) {
            command = WindowsCommandRetriever.getCommandForFileType("https");
        } else if (urlLC.startsWith("http")) {
            command = WindowsCommandRetriever.getCommandForFileType("http");
        }
        if (command == null) {
            command = WindowsCommandRetriever.commandForExtension(".html");
        }
        if (command.indexOf("%1") > -1) {
            sb.append(command.substring(0, command.indexOf("%1")));
            sb.append(url);
            sb.append(command.substring(command.indexOf("%1") + "%1".length()));
        } else {
            sb.append(command).append(' ');
            sb.append('"');
            sb.append(url);
            sb.append('"');
        }
    } else {
        sb.append("open ");
        sb.append(url);
    }
    try {
        final Process p = Runtime.getRuntime().exec(sb.toString());
        // Here you have the process. You can destroy it if you want
        // You need to figure out how you are going to handle this here.
    } catch (IOException e1) {
        e1.printStackTrace();
        System.err.println("Error while executing " + sb.toString());
    }
}

而WindowsCommandRetriever:

And the WindowsCommandRetriever:

/*
 * (c) Copyright 2010-2011 AgileBirds
 *
 * This file is part of OpenFlexo.
 *
 * OpenFlexo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * OpenFlexo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
 *
 */

public class WindowsCommandRetriever {
    /**
     * 
     * @param extension
     *            the file extension (with or without the preceding '.')
     * @return the command to execute for the specified <code>extension</code> or null if there are no associated command
     */
    public static String commandForExtension(String extension) {
        String regKey = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\" + extension;
        String fileType = WinRegistryAccess.getRegistryValue(regKey, "ProgID", WinRegistryAccess.REG_SZ_TOKEN);
        if (fileType == null) {
            StringBuilder sb = new StringBuilder("cmd /C assoc ");
            sb.append(extension.startsWith(".") ? extension : "." + extension);

            ConsoleReader reader;
            try {
                Process process = Runtime.getRuntime().exec(sb.toString());
                reader = new ConsoleReader(process.getInputStream());
                reader.start();
                process.waitFor();
                reader.join();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            }
            String result = reader.getResult();
            if (result.indexOf("=") > -1) {
                fileType = result.substring(result.indexOf("=") + 1).trim();
            }
        }
        if (fileType == null) {
            return null;
        }
        return getCommandForFileType(fileType);
    }

    public static String getCommandForFileType(String fileType) {
        String path = "HKEY_CLASSES_ROOT\\" + fileType + "\\shell\\open\\command";
        return WinRegistryAccess.getRegistryValue(path, null, WinRegistryAccess.REG_SZ_TOKEN);
    }
}


/*
 * (c) Copyright 2010-2011 AgileBirds
 *
 * This file is part of OpenFlexo.
 *
 * OpenFlexo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * OpenFlexo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
 *
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;


public class WinRegistryAccess {

    private static final String REGQUERY_UTIL = "reg query ";

    public static final String REG_SZ_TOKEN = "REG_SZ";

    public static final String REG_BINARY = "REG_BINARY";

    public static final String REG_DWORD_TOKEN = "REG_DWORD";

    /**
     * Returns the value for an attribute of the registry in Windows. If you want to now the processor speed of the machine, you will pass
     * the following path: "HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" and the following attribute name: ~MHz
     * 
     * @param path
     *            - the registry path to the desired value
     * @param attributeName
     *            - the name of the attribute or null for the default
     * @param attributeType
     *            - the type of attribute (DWORD/SZ/...) default is REG_SZ
     * @return - the value for the attribute located in the given path
     */
    public static String getRegistryValue(String path, String attributeName, String attributeType) {
        if (attributeType == null) {
            attributeType = REG_SZ_TOKEN;
        }
        try {
            if (!path.startsWith("\"")) {
                path = "\"" + path + "\"";
            }
            StringBuilder sb = new StringBuilder();
            sb.append(REGQUERY_UTIL);
            sb.append(path);
            sb.append(' ');
            if (attributeName != null) {
                sb.append("/v ");
                sb.append(attributeName);
            } else {
                sb.append("/ve");
            }
            Process process = Runtime.getRuntime().exec(sb.toString());
            ConsoleReader reader = new ConsoleReader(process.getInputStream());
            reader.start();
            process.waitFor();
            reader.join();
            String result = reader.getResult();
            int p = result.indexOf(attributeType);
            if (p == -1) {
                return null;
            }
            return result.substring(p + attributeType.length()).trim();
        } catch (Exception e) {
            return null;
        }
    }

    public static class ConsoleReader extends Thread {
        private InputStream is;

        private StringWriter sw;

        ConsoleReader(InputStream is) {
            this.is = is;
            sw = new StringWriter();
        }

        @Override
        public void run() {
            try {
                int c;
                while ((c = is.read()) != -1) {
                    sw.write(c);
                }
            } catch (IOException e) {
                ;
            }
        }

        String getResult() {
            return sw.toString();
        }
    }

    public static String getJDKHome() {
        String key = "\"HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\"";
        String currentVersionAtt = "CurrentVersion";
        String javaHomeAtt = "JavaHome";
        String res1 = getRegistryValue(key, currentVersionAtt, null);
        String res2 = getRegistryValue(key + "\\" + res1, javaHomeAtt, null);
        return res2;
    }

    public static void main(String s[]) {
        String key = "\"HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\"";
        String currentVersionAtt = "CurrentVersion";
        String javaHomeAtt = "JavaHome";
        String res1 = getRegistryValue(key, currentVersionAtt, null);
        String res2 = getRegistryValue(key + "\\" + res1, javaHomeAtt, null);
        System.out.println("CurrentVersion '" + res1 + "'");
        System.out.println("JavaHome '" + res2 + "'");
    }
}

这篇关于从java程序关闭Web浏览器对特定URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆