【问题标题】:webkitgtk how to control resource loading depends on the type of the resource?webkitgtk 如何控制资源加载取决于资源的类型?
【发布时间】:2013-08-23 06:44:03
【问题描述】:

我想根据css、script、img等资源的类型来控制资源下载。

我正在测试从 loacl 加载 html 并使用 WebkitGtk 操作 DOM 的东西。 我可以通过 WebkitGtk 从本地文件加载 html。

但如您所知,有一些资源可供下载,例如 img、css 或脚本。我根本不想下载那些。 对于 img 和 script,我可以通过设置 WebKitWebSettings (的 WebkitGtk )来做到这一点。

但是没有办法在 WebKitWebSettings 中阻止 css。 所以我尝试通过挂钩“resource-request-starting”信号来做到这一点。

static void loadStatusCb(WebKitWebView *web_view, GParamSpec *pspec, void* context);

我可以通过挂钩来阻止所有网络请求。 但我不想阻止所有资源下载。 我要阻止取决于类型(css、script、img、...)

例如,如果 test_file 请求来自

<link type="text/css" rel="stylesheet" href="http://test.com/test_file">

我会阻止。因为是css。

但是从

<script type="text/javascript" src="http://test.com/test_file"></script>

我不会阻止。

我试图从 WebKitWebRequest 的 SoupMessage 中获取任何信息。但我无法获得任何信息,但不是 uri。

如果您知道任何方法可以做到这一点,请回复。 提前致谢。

【问题讨论】:

    标签: webkit gtk


    【解决方案1】:

    resource-request-starting 信号接受多个参数,其中一个可能对您非常有用:WebKitWebResource 类的对象,该类具有 webkit_web_resource_get_mime_type 方法。

    您需要遵循WebKitGtk+ documentation 中描述的resource-request-starting 信号处理程序原型:

    void user_function (WebKitWebView *webView,
                        WebKitWebFrame        *web_frame,
                        WebKitWebResource     *web_resource,
                        WebKitNetworkRequest  *request,
                        ebKitNetworkResponse *response,
                        gpointer user_data) 
    

    【讨论】:

    • 首先,感谢您的回答:)。我试过但我无法从 web_resource 获得任何信息。没有 mime_type 我能得到。我正在使用 webkit 1.6.1。我把这个函数称为'webkit_web_resource_get_mime_type(resource)'。我做错了吗??
    • 我猜钓鱼不是所有男人的任务...... :)
    【解决方案2】:

    您可以连接到 WebView 的“mime-type-policy-decision-requested”信号。

    在回调中,检查 mimetype 是否不受欢迎,然后将策略决策设置为 IGNORE,然后返回 TRUE,这意味着您处理了信号。我手头有一个 python 解决方案:

    def __mime_type_policy_cb(self, webview, frame, request, mimetype,
                              policy_decision):
        """Handle downloads and PDF files."""
        if mimetype == 'application/pdf':
            self.emit('open-pdf', request.get_uri())
            policy_decision.ignore()
            return True
    

    【讨论】:

      【解决方案3】:

      正如好人 eagleoneraptor 所说,您需要遵循resource-request-starting 信号,但我想您需要一个完整的解决方案。主要思想是在发送之前获取请求,并通过WebKitNetworkRequest.set_uri(str) 将它的uri 设置为您想要的东西或about:blank。这是它的样子:

          def test(web_view, frame, web_resource, request, response):
              print request.get_uri()
              if (YOUR_CONDITION_BASED_ON_URI):
                  request.set_uri('about:blank')
      
          web_view.connect('resource-request-starting', test)
      

      【讨论】:

        猜你喜欢
        • 2021-06-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 1970-01-01
        相关资源
        最近更新 更多