【问题标题】:How to load user CSS in a WebKit WebView using PyObjC?如何使用 PyObjC 在 WebKit WebView 中加载用户 CSS?
【发布时间】:2011-11-05 12:11:13
【问题描述】:

我想要一个使用我自己的 CSS 的小型浏览器。 问题是 CSS 没有加载,或者我猜它加载但没有任何效果。

这是完整的代码(我不使用 Interface Builder):

import Foundation
import WebKit
import AppKit
import objc

def main():
    app = AppKit.NSApplication.sharedApplication()
    rect = Foundation.NSMakeRect(100,350,600,800)
    win = AppKit.NSWindow.alloc()
    win.initWithContentRect_styleMask_backing_defer_(rect, AppKit.NSTitledWindowMask | AppKit.NSClosableWindowMask | AppKit.NSResizableWindowMask | AppKit.NSMiniaturizableWindowMask, AppKit.NSBackingStoreBuffered, False)
    win.display()
    win.orderFrontRegardless()

    webview = WebKit.WebView.alloc()
    webview.initWithFrame_(rect)

    webview.preferences().setUserStyleSheetEnabled_(objc.YES)
    print webview.preferences().userStyleSheetEnabled()
    cssurl = Foundation.NSURL.URLWithString_("http://dev.stanpol.ru/user.css")
    webview.preferences().setUserStyleSheetLocation_(cssurl)
    print webview.preferences().userStyleSheetLocation()

    pageurl = Foundation.NSURL.URLWithString_("http://dev.stanpol.ru/index.html")
    req = Foundation.NSURLRequest.requestWithURL_(pageurl)
    webview.mainFrame().loadRequest_(req)

    win.setContentView_(webview)
    app.run()

if __name__ == '__main__':
    main()

代码运行没有错误。打印

True
http://dev.stanpol.ru/user.css

但我的 CSS 在 WebView 中没有效果。

我尝试了不同的解决方案,例如向 DOM 添加链接:

pageurl = Foundation.NSURL.URLWithString_("http://dev.stanpol.ru/index.html")
req = Foundation.NSURLRequest.requestWithURL_(pageurl)
webview.mainFrame().loadRequest_(req)

dom = webview.mainFrame().DOMDocument()
link = dom.createElement_("link")
link.setAttribute_value_("rel", "StyleSheet")
link.setAttribute_value_("type", "text/css")
link.setAttribute_value_("href", "http://dev.stanpol.ru/user.css")

head = dom.getElementsByTagName_(u"head")
hf = head.item_(0)
hf.appendChild_(link)

但无论哪种情况,它都不起作用。

我不想使用 javascript 来加载 CSS。

谁能告诉我在我的代码中设置用户 CSS 有什么问题?

【问题讨论】:

    标签: python objective-c css webkit pyobjc


    【解决方案1】:

    Apple 没有正确记录 setUserStyleSheetLocation 只能是本地路径或数据:URL。 Qt 确实在他们的 QtWebKit 中相应设置的文档中解释了这一点:

    http://doc.qt.nokia.com/latest/qwebsettings.html#setUserStyleSheetUrl

    指定每个网页加载的用户样式表的位置 页面。

    位置必须是本地文件系统上的路径,或者 带有 UTF-8 和 Base64 编码数据的数据 URL,例如:

    "data:text/css;charset=utf-8;base64,cCB7IGJhY2tncm91bmQtY29sb3I6IHJlZCB9Ow=="

    注意:如果base64数据无效,样式将不会被应用。

    【讨论】:

      猜你喜欢
      • 2011-09-22
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多