-
Hi, I have a subclass of TabContentScript that I use to be notified of any DOM modifications. This worked fine until Setting Anyway, here is my class: class DOMMutationHelper: TabContentScript {
fileprivate weak var tab: Tab?
fileprivate static let marker : String = UUID().uuidString
init(tab: Tab) {
self.tab = tab
}
static func name() -> String {
return "com_my_mutation"
}
func scriptMessageHandlerName() -> String? {
return "myMutationHelper"
}
func userContentController(_ userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage) {
guard let data = message.body as? [String: Any?]
, let callMarker = data["marker"] as? String, callMarker == DOMMutationHelper.marker
, let innerHTML = (data["innerHTML"] as? String)?.nonEmpty
, let webView = tab?.currentWebView()
else {
return
}
// Call down to our custom func in BrowserViewController
tab?.browserViewController?.innerHTMLDidChange(innerHTML, inWebView: webView)
}
static func associatedUserScript() -> WKUserScript {
let endScript = """
const observer = new MutationObserver(list => {
console.log("mutation list", list);
if (["http:", "https:"].includes(window.location.protocol)) {
webkit.messageHandlers.myMutationHelper.postMessage({
"marker": "\(marker)",
"mutations": list.length,
"innerHTML": document.documentElement.innerHTML,
});
} else {
console.log("Ignoring mutation for protocol:", window.location.protocol);
}
});
observer.observe(document.body, {
attributes: false,
childList: true,
characterData: true,
subtree: true
});
console.log("mutation observer installed");
"""
return WKUserScript(source: endScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
}
} The script gets added to the current tab just after the FocusHelper script in BrowserViewController.tab(...): tab.addContentScript(FocusHelper(tab: tab), name: FocusHelper.name())
tab.addContentScript(DOMMutationHelper(tab: tab), name: DOMMutationHelper.name()) and it gets installed into the web view in UserScriptManager.injectUserScriptsIntoTab(...) at the end: if noImageMode {
tab.webView?.configuration.userContentController.addUserScript(noImageModeUserScript)
}
let script = DOMMutationHelper.associatedUserScript()
tab.webView?.configuration.userContentController.addUserScript(script) Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @gutley Could you try and replace
with
If that doesn't work you could try
|
Beta Was this translation helpful? Give feedback.
Hey @gutley
Could you try and replace
with
If that doesn't work you could try