“MỌI SỰ CỐ GẮNG CHƯA CHẮC ĐÃ GẶT HÁI ĐƯỢC KẾT QUẢ NHƯNG MỖI KẾT QUẢ ĐẠT ĐƯỢC CHẮC CHẮN LÀ CẢ MỘT QUÁ TRÌNH CỐ GẮNG”

JavaScript HTMLEditor chèn liên kết vào văn bản được chọn và mở với trình duyệt mặc

Thứ sáu - 22/03/2024 13:12

JavaScript trong HTMLEditor chèn liên kết vào phần văn bản được chọn và mở với trình duyệt mặc định

JavaScript HTMLEditor chèn liên kết vào văn bản được chọn và mở với trình duyệt mặc

1) JavaScript lưu trong thư mục “resources\js\selectionHandler.js”; “resources\js\selectedText.js”

document.addEventListener('selectionchange', function() {
    var selection = window.getSelection().toString();
    java.selectionChanged(selection !== '');
});
document.addEventListener('selectionchange', function() {
    var selection = window.getSelection().toString().trim();
    java.getSelectedText(selection);
});

HTMLEditorSelectTextLinkInsert

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebView;
import javafx.scene.web.WebEngine;

import javafx.scene.control.ToolBar;
import javafx.scene.control.Tooltip;
import netscape.javascript.JSObject;

public class HTMLEditorSelectTextLinkInsert extends Application {

    String selection;
    private final Button insertLinkButton = new Button("Chèn liên kết");

    @Override
    public void start(Stage primaryStage) {
        // Tạo một HTMLEditor
        HTMLEditor htmlEditor = new HTMLEditor();

        // Lấy toolbar của HTMLEditor
        ToolBar bar = (ToolBar) htmlEditor.lookup(".top-toolbar");
        if (bar != null) {
            insertLinkButton.setTooltip(new Tooltip("Chèn liên kết vào phàn văn bản được chọn"));
            insertLinkButton.setDisable(true); // Ban đầu, nút sẽ bị tắt

            WebView webView = (WebView) htmlEditor.lookup(".web-view");
            WebEngine webEngine = webView.getEngine();
            webEngine.documentProperty().addListener((observable, oldValue, newValue) -> {
                JSObject window = (JSObject) webEngine.executeScript("window");
                window.setMember("java", this);
                String filePath = "/js/selectionHandler.js";
                String script = readScriptFile(filePath);
                webEngine.executeScript(script);

                filePath = "/js/selectedText.js";
                script = readScriptFile(filePath);
                webEngine.executeScript(script);
            });

            insertLinkButton.setOnAction(event -> {
                if (!selection.isEmpty()) {
                    String ok = askForLinkUrl();
                    if (ok != null) {
                        String linkUrl = ok;
                        String linkedText = "<a href=\"" + linkUrl + "\">" + selection + "</a>";
                        webEngine.executeScript("document.execCommand('insertHTML', false, '" + linkedText + "')");
                    }
                }
            });

            webEngine.locationProperty().addListener((observable, oldValue, newValue) -> {
                if (newValue != null) {
                    htmlEditor.setHtmlText(htmlEditor.getHtmlText());
                    try {
                        URI uri = new URI(newValue);
                        if (uri.getScheme() != null && (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https"))) {                                                   
                            getHostServices().showDocument(uri.toString());
                        }
                    } catch (URISyntaxException e) {
                    }
                }
            });           
            bar.getItems().add(insertLinkButton);
        }

        // Tạo Scene và hiển thị
        Scene scene = new Scene(htmlEditor, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.setTitle("HTMLEditor với chèn ảnh");
        primaryStage.show();
    }

    // Phương thức để đọc nội dung của tệp JavaScript địa chỉ tương đối
    private String readScriptFile(String filePath) {
        try {
            StringBuilder contentBuilder = new StringBuilder();
            InputStream is = getClass().getResourceAsStream(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
            return contentBuilder.toString();

        } catch (IOException e) {
            return null;
        }
    }

// Được gọi từ JavaScript khi sự kiện selectionchange xảy ra
    public void selectionChanged(boolean hasSelection) {
        insertLinkButton.setDisable(!hasSelection); // Vô hiệu hóa nút lệnh Copy nếu không có văn bản được chọn
    }

    // Được gọi từ JavaScript khi sự kiện selectionchange xảy ra
    public void getSelectedText(String text) {
        selection = text;        
    }
    private String askForLinkUrl() {
        String uridefault = "https://365.io.vn";
        System.out.println(selection);
        if ((selection.startsWith("http://")) || (selection.startsWith("https://"))) {
            uridefault = selection;
        }
        TextInputDialog dialog = new TextInputDialog(uridefault);
        dialog.setTitle("Insert Link");
        dialog.setHeaderText("Enter the URL for the hyperlink:");
        dialog.setContentText("URL:");
        return dialog.showAndWait().orElse(null);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

- Kết quả:

 

Tác giả: Vàng Văn Quyn

Tổng số điểm của bài viết là: 0 trong 0 đánh giá

Click để đánh giá bài viết
Thống kê
  • Đang truy cập15
  • Hôm nay2,221
  • Tháng hiện tại83,179
  • Tổng lượt truy cập9,174,722
Bạn đã không sử dụng Site, Bấm vào đây để duy trì trạng thái đăng nhập. Thời gian chờ: 60 giây