2011-08-28 24 views
9

我想要一個使用我自己的CSS的小型瀏覽器。 問題是,CSS未加載或,我猜,它加載,但沒有任何影響。如何使用PyObjC在WebKit WebView中加載用戶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 

但我的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有什麼問題嗎?

回答

3

Apple沒有正確記錄該setUserStyleSheetLocation只能是本地路徑或數據:URL。 Qt的確實在QtWebKit的解釋它們的相應設置的文件中:

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

指定用戶樣式表的位置與每個web 頁面加載。

必須是在本地文件系統的路徑,或使用UTF-8和Base64編碼數據,諸如 數據URL位置:

「的數據:文本/ CSS;字符集= UTF-8; base64,cCB7IGJhY2tncm91bmQtY29sb3I6IHJlZCB9Ow ==「

注意:如果base64數據無效,該樣式將不會應用。

相關問題