我试图复制'window.location.href‘,例如,当前页面的网址,从我的扩展到剪贴板。
我的问题是,当我将URL复制到剪贴板时,复制的是扩展URL,而不是我正在访问的页面。
扩展条:
<!DOCTYPE HTML>
<html>
<head>
<button onclick="copyFunction();">Copy</button>
<script type="text/javascript">
function copyFunction() {
var inputDump = document.createElement('input'),
hrefText = window.location.href;
document.body.appendChild(inputDump);
inputDump.value = hrefText;
inputDump.select();
document.execCommand('copy');
document.body.removeChild(inputDump);
}
</script>
</head>
</html>根据我的理解,解决方案应该是这样的,但恐怕我太不知道如何继续下去了:脚本
这就是我(试图)通过创建一个global.html页面和一个注入的脚本来进行的。
全球页面:
<!DOCTYPE HTML>
<script>
safari.application.addEventListener("command", copyFunction, false);
function copyFunctionEvent(event) {
if (event.command == "CopyToClipboard") {
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("CopyToClipboard", "all");
}
}
</script>注入脚本:
function myextension_openAll(event){
if (event.name == 'CopyToClipboard'){
function copyFunction() {
var inputDump = document.createElement('input'),
hrefText = window.location.href;
document.body.appendChild(inputDump);
inputDump.value = hrefText;
inputDump.select();
document.execCommand('copy');
document.body.removeChild(inputDump);
}
}
safari.self.addEventListener("message", myextension_openAll, true);safari-extension://com.myextension-0000000000/abc123/extensionbar.html 实数:
预期: http://www.google.com (例如,如果当前选项卡)
发布于 2019-02-10 01:51:58
从上面的代码(Extensionbar html)来看,您似乎编写了遗留的Safari扩展(.safariextz),并且已经不再推荐它了。请参阅在Safari和WebKit中什么是新的“WWDC18会话”
我建议您通过以下过程将代码重写为Safari应用程序扩展,这个过程可以用Swift编写。我不知道为什么会将错误的URL复制到代码中的剪贴板中,但是重写代码会解决问题。
创建应用程序扩展项目
创建应用程序扩展通过以下文件->新->项目..。然后选择Xcode上的Safari扩展应用程序。项目模板包含菜单实现的示例。
单击菜单栏按钮复制location.href
以下代码将在单击菜单栏按钮时添加复制location.href的功能。
只需将其粘贴到SafariExtensionHandler.swift。
class SafariExtensionHandler: SFSafariExtensionHandler {
override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) {
// WHen injected script calls safari.extension.dispatchMessage, the message will come here
guard let href = userInfo?["href"] as? String else { return }
// Save href to clipboard
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(href, forType: .string)
}
override func toolbarItemClicked(in window: SFSafariWindow) {
// Request injected script a message to send location.href
window.getActiveTab { currentTab in
currentTab!.getActivePage { currentPage in
currentPage!.dispatchMessageToScript(withName: "getHref", userInfo: nil)
}
}
}
}和注入脚本(script.js)如下。
safari.self.addEventListener("message", function(event) {
console.log("event received");
safari.extension.dispatchMessage("sendHref", { "href": location.href });
});工作实例
在这里完成工作代码,这可能对你的工作有所帮助。祝你好运:)
https://github.com/horimislime/safari-extension-menubar-example
https://stackoverflow.com/questions/53976304
复制相似问题