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

Sta*_*pol 9 css python pyobjc webkit objective-c

我想要一个使用我自己的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()
Run Code Online (Sandbox Code Playgroud)

代码运行没有错误.打印

True
http://dev.stanpol.ru/user.css
Run Code Online (Sandbox Code Playgroud)

但是我的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)
Run Code Online (Sandbox Code Playgroud)

但在任何一种情况下它都不起作用.

我不想使用javascript加载CSS.

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

Dav*_*ess 3

Apple 没有正确记录 setUserStyleSheetLocation 只能是本地路径或 data: URL。Qt 在 QtWebKit 中相应设置的文档中对此进行了解释:

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

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

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

“数据:文本/ CSS;字符集= utf-8;base64,cCB7IGJhY2tncm91bmQtY29sb3I6IHJlZCB9Ow ==”

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