javascript EventListener未激发-动态创建和下载日历事件

h22fl7wq  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(157)

我正在获取outlook日历事件的纯文本,并将其转换为ics,以便用Tampermonkey下载。
几年前我写这篇文章的时候,这个按钮还能用,但现在不行了。我不确定我现在是否需要授予权限,或者是其他什么东西破坏了它。这个按钮添加得很好,但我无法触发事件侦听器。

// .....
// @grant        none
//=====    convert text only calendar to a donwloadable ICS file
elementReady('#desc-content').then((element) => {
  //grab the relevant text
  if (element.innerHTML.includes("BEGIN:VCALENDAR")) {
    //clean up some bit
    var calendar = element.innerHTML.substring(0, element.innerHTML.length - '<div class="clearfix"></div>'.length).replace(/<br\s*[\/]?>/gi, '\n');
    //Create a button element 
    var CalendarEventButton = document.createElement("button");
    CalendarEventButton.innerHTML = 'Download Calendar Event';

    CalendarEventButton.addEventListener("click", function() {
      var filename = "CalendarInvite.ics"; //File name that will be downloaded
      download(filename, calendar); //passing in the file name and text to be downloaded
    }, false);

    element.appendChild(CalendarEventButton); //append the button to the document
  }
});

/* Download an embedded file/text*/
function download(file, text) {

  //creating an invisible element
  var element = document.createElement('a');
  element.setAttribute('href',
    'data:text/calendar;charset=utf-8, ' +
    encodeURIComponent(text));
  element.setAttribute('download', file);

  // Above code is equivalent to
  // <a href="path of file" download="file name">

  document.body.appendChild(element);

  //onClick property
  element.click();

  document.body.removeChild(element);
}
hkmswyz6

hkmswyz61#

1.使用const(ES 2015+)代替var(〈= ES 5)。
1.已克隆元素,以便以更可靠的方式删除div.clearfix
1.使用的模板字符串('....')。
1.使用本机GM_download方法进行更轻松/可靠的下载。

// .....
// @grant        GM_download
//=====    convert text only calendar to a donwloadable ICS file
elementReady('#desc-content').then((element) => {
  // grab the relevant text
  const cloned = element.cloneNode(true);

  if (!cloned.innerText.includes("BEGIN:VCALENDAR")) return;

  // clean up some bit

  // use the cloned element so that removing clearfix div
  // won't affect DOM
  cloned.querySelector('.clearfix')?.remove();
  const calendar = cloned.innerHTML.replace(/<br\s*[\/]?>/gi, '\n');

  // Create a button element 
  const calendarEventButton = document.createElement("button");
  calendarEventButton.innerHTML = 'Download Calendar Event';

  calendarEventButton.addEventListener("click", function() {
    const filename = "CalendarInvite.ics"; // File name that will be downloaded

    download(filename, calendar); // passing in the file name and text to be downloaded
  }, false);

  element.appendChild(calendarEventButton); //append the button to the document
});

/* Download an embedded file/text*/
function download(file, text) {
  const encoded = encodeURIComponent(text);
  const downloadable = `data:text/calendar;charset=utf-8, ${encoded}`;

  GM_download(downloadable, file);
}

相关问题