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

标签 python objective-c css webkit pyobjc

我想要一个使用我自己的 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/

相关文章:

python - 使用色调选项从 pandas db 和seaborn 的 fiddle 图制作多个图

python - python 中表 <td/> 的内联 CSS 语句

objective-c - UIViewControllers 问题

python - 检查列内的字符串错误行为 - Pandas

python - 列表成员测试或集合

objective-c - 第二个工具栏,如 NSScrollView 下的邮件 + 工具栏

iphone - 如何在键盘处于事件状态时隐藏 iPhone 上的文本字段光标

css - IE9中的子导航被推到导航之上

javascript - 在javascript中跨域访问css文件中的CSS类

html - CSS 选择器,div 输入 :checked