如何在WebKit WebView中使用PyObjC加载用户CSS?

9 投票
1 回答
1437 浏览
提问于 2025-04-17 00:29

我想做一个小浏览器,能用我自己的CSS样式。问题是CSS没有加载,或者我猜是加载了,但没有任何效果。

这是完整的代码(我没有使用界面构建工具):

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

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

我尝试了不同的解决方案,比如往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有什么问题吗?

1 个回答

3

苹果并没有清楚说明 setUserStyleSheetLocation 只能是本地路径或者数据 URL。Qt 在他们的文档中对这个设置做了详细的解释:

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

这个设置指定了一个用户样式表的位置,这个样式表会在每个网页加载时使用。

这个位置必须是本地文件系统中的路径,或者是一个包含 UTF-8 和 Base64 编码数据的数据 URL,比如:

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

注意:如果这个 Base64 数据不正确,样式就不会被应用。

撰写回答