有没有办法使用谷歌的Apps Script
在边栏中创建一个复制到剪贴板的按钮?
我当前的代码如下,但复制按钮不起作用:
function createCalendarEvent() {
var html = HtmlService.createHtmlOutput()
.setTitle("Πληροφορίες για Ημερολόγιο")
.setContent('<div><p id="item-to-copy">Test</p>' + 'nn<button onclick='+"copyToClipboard()"+'>Copy</button></div>')
var ui = SpreadsheetApp.getUi(); // Or DocumentApp or SlidesApp or FormApp.
ui.showSidebar(html);
}
function copyToClipboard() {
const str = document.getElementById('item-to-copy').innerText;
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el(;}
第二个函数是javascipt。
你能帮我吗?
编辑当我在浏览器上单击F12时,我得到以下错误:
Uncaught ReferenceError: copyToClipboard is not defined
at HTMLButtonElement.onclick (userCodeAppPanel:1)
onclick @ userCodeAppPanel:1
修改点:
- 从
The second function is javascipt.
开始,在脚本中,如果copyToClipboard()
被放在脚本编辑器的HTML文件中,在这种情况下,脚本中的html
不包括该函数。这样,就会出现这样的错误 - 或者,如果
copyToClipboard()
被放在脚本编辑器的Google Apps脚本文件中,则copyToClipboard()
不能从HTML端运行。这样,就会出现这样的错误
为了运行copyToClipboard()
,我想提出以下修改。
修改的脚本:
HTML&Javascript端:
请将以下脚本复制并粘贴到谷歌应用程序脚本项目中脚本编辑器的HTML文件中。文件名为index.html
。
<div>
<p id="item-to-copy">Test</p>
<button onclick="copyToClipboard()">Copy</button>
</div>
<script>
function copyToClipboard() {
const str = document.getElementById('item-to-copy').innerText;
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
</script>
谷歌应用程序脚本端:
请将以下脚本复制并粘贴到Google Apps脚本项目中脚本编辑器的Google Apps script文件中。
function createCalendarEvent() {
var html = HtmlService.createHtmlOutputFromFile("index").setTitle("Πληροφορίες για Ημερολόγιο")
var ui = SpreadsheetApp.getUi(); // Or DocumentApp or SlidesApp or FormApp.
ui.showSidebar(html);
}
createCalendarEvent()
运行时,脚本加载HTML&index.html
文件中的Javascript
注意:
如果要使用
setContent
,还可以使用以下脚本。HTML&Javascript端:
<script> function copyToClipboard() { const str = document.getElementById('item-to-copy').innerText; const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); } </script>
谷歌应用程序脚本端:
function createCalendarEvent() { var javascript = HtmlService.createHtmlOutputFromFile("index").getContent(); var htmlData = `<div><p id="item-to-copy">Test</p><button onclick="copyToClipboard()">Copy</button></div>${javascript}`; var html = HtmlService.createHtmlOutput() .setTitle("Πληροφορίες για Ημερολόγιο") .setContent(htmlData) var ui = SpreadsheetApp.getUi(); // Or DocumentApp or SlidesApp or FormApp. ui.showSidebar(html); }
参考文献:
- 类HtmlService
- HTML服务:创建和提供HTML