I'd like to have a small browser that uses my own CSS. The problem is that CSS is not loaded or, I guess, it loads but without any effect.
Here is the full code (I don't use an 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()
The code runs without errors. Prints
True
http://dev.stanpol.ru/user.css
but there is no effect of my CSS in the WebView.
I tried different solutions like adding a link to the 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)
but in either case it doesn't work.
I don't want to use javascript to load CSS.
Can anybody tell me what's wrong with setting user CSS in my code?
Apple doesn't properly document that setUserStyleSheetLocation can only be a local path or data: URL. Qt does explain this in their documentation of the corresponding setting in 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With