Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Execute print user script in page content world #238

Merged
merged 3 commits into from
Nov 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions DuckDuckGo/BrowserTab/Model/PrintingUserScript.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,17 @@ public protocol PrintingUserScriptDelegate: AnyObject {
}

public class PrintingUserScript: NSObject, UserScript {
public var requiresRunInPageContentWorld: Bool {
return true
}

public weak var delegate: PrintingUserScriptDelegate?

public var source: String = """
(function() {
document.addEventListener("click", function(event) {

let onClickAttribute = event.target.getAttribute('onclick');

if (onClickAttribute && onClickAttribute.includes('window.print()')) {
webkit.messageHandlers.printHandler.postMessage({});
}
});
window.print = function() {
webkit.messageHandlers.printHandler.postMessage({});
};
alistairjcbrown marked this conversation as resolved.
Show resolved Hide resolved
}) ();
"""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ extension WKUserContentController {
func addHandler(_ userScript: UserScript) {
for messageName in userScript.messageNames {
if #available(macOS 11.0, *) {
let contentWorld: WKContentWorld = userScript.getContentWorld()
if let handlerWithReply = userScript as? WKScriptMessageHandlerWithReply {
addScriptMessageHandler(handlerWithReply, contentWorld: .defaultClient, name: messageName)
addScriptMessageHandler(handlerWithReply, contentWorld: contentWorld, name: messageName)
} else {
add(userScript, contentWorld: .defaultClient, name: messageName)
add(userScript, contentWorld: contentWorld, name: messageName)
}
} else {
add(userScript, name: messageName)
Expand All @@ -45,7 +46,8 @@ extension WKUserContentController {
func removeHandler(_ userScript: UserScript) {
userScript.messageNames.forEach {
if #available(macOS 11.0, *) {
removeScriptMessageHandler(forName: $0, contentWorld: .defaultClient)
let contentWorld: WKContentWorld = userScript.getContentWorld()
removeScriptMessageHandler(forName: $0, contentWorld: contentWorld)
} else {
removeScriptMessageHandler(forName: $0)
}
Expand Down