2010-07-13 68 views
10

比方說,我想在GTK中使用WebKitWebView來顯示一些靜態HTML頁面。這些頁面使用自定義URL方案,我們稱之爲custom://。這個方案代表了一個本地文件,在生成HTML時,它的位置並不是事先知道的。我要做的就是連接到網頁視圖的navigation-requested信號,而做到這一點:如何處理Webkit GTK中的自定義URL方案?

const gchar *uri = webkit_network_request_get_uri(request); 
gchar *scheme = g_uri_parse_scheme(uri); 

if(strcmp(scheme, "custom") == 0) { 
    /* DO FILE LOCATING MAGIC HERE */ 
    webkit_web_view_open(webview, real_location_of_file); 
    return WEBKIT_NAVIGATION_RESPONSE_IGNORE; 
} 
/* etc. */ 

這似乎做工精細,除該計劃是在<img>標籤中使用,例如:<img src="custom://myfile.png">,顯然這些不請通過navigation-requested信號。

在我看來,應該有一些方法來爲Webkit註冊自定義URL方案的處理程序。這可能嗎?

回答

5

我更熟悉WebKit的Chromium端口,但我相信您可能需要使用webkit_web_resource_get_uri(請參閱webkitwebresource.h)來處理資源(如圖像)。

+3

謝謝,這是我需要正確的方向指針。爲了完整起見,答案是連接到webview的'resource-request-starting'信號,並使用該處理程序中的'webkit_web_resource_get_uri()'進行操作。 (請注意,這僅適用於webkit> = 1.1.14。) – ptomato 2010-07-18 13:48:50

2

In WebKit GTK 2, there is a more official route for this:

WebKitWebContext *context = webkit_web_context_get_default(); 
webkit_web_context_register_uri_scheme(context, "custom", 
    (WebKitURISchemeRequestCallback)handle_custom, 
    NULL, NULL); 

/* ... */ 

static void 
handle_custom(WebKitURISchemeRequest *request) 
{ 
    /* DO FILE LOCATING MAGIC HERE */ 
    GFile *file = g_file_new_for_path(real_location_of_file); 
    GFileInputStream *stream = g_file_read(file, NULL, NULL); 
    g_object_unref(file); 

    webkit_uri_scheme_request_finish(request, stream, -1, NULL); 
    g_object_unref(stream); 
} 
+0

這是一個更好的答案。 – clee 2018-02-20 06:37:58