我想要一个使用我自己的 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 有什么问题吗?
最佳答案
Apple 没有正确记录 setUserStyleSheetLocation 只能是本地路径或数据:URL。 Qt 在 QtWebKit 中相应设置的文档中对此进行了解释:
http://doc.qt.nokia.com/latest/qwebsettings.html#setUserStyleSheetUrl
Specifies the location of a user stylesheet to load with every web page.
The location must be either a path on the local filesystem, or a data URL with UTF-8 and Base64 encoded data, such as:
"data:text/css;charset=utf-8;base64,cCB7IGJhY2tncm91bmQtY29sb3I6IHJlZCB9Ow=="
Note: If the base64 data is not valid, the style will not be applied.
关于python - 如何使用 PyObjC 在 WebKit WebView 中加载用户 CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7221699/