【发布时间】:2019-02-10 09:51:58
【问题描述】:
我正在尝试复制“window.location.href”,例如当前页面的 URL 从我的扩展程序到剪贴板。
我的问题是,当我将 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>
根据我的理解,解决方案应该是这样的,但我担心我太无能为力了:https://developer.apple.com/documentation/safariservices/safari_app_extensions/passing_messages_between_safari_app_extensions_and_injected_scripts
这就是我(试图)通过创建 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(例如,如果当前选项卡)
【问题讨论】:
-
也许
safari.application.activeBrowserWindow.activeTab.url?我对 Safari 扩展一无所知,这个答案有 0 票赞成,所以以防万一。 -
谢谢 Jeto,我也试过这个,但对我来说问题主要是我不确定如何在我的 extensionbar.html、global.html 和注入的脚本之间正确通信。我怕我迷路了。 :)
标签: javascript html safari-extension