window.alert() 在打包的应用程序中不可用

window.alert() is not available in packaged apps

我正在申请 Chrome。我不断在控制台中收到错误消息:

window.alert() is not available in packaged apps. extensions::platformApp:17

该文件的第 17 行只是将错误记录到控制台的一行代码。有没有办法提醒用户 chrome 应用程序中的事件(例如 image?)是因为我在 Firefox 中安装了 adblock(我不使用 Chrome) ?我认为 alert() 非常基础。谢谢你的帮助。

alert 功能已在 Chrome 打包应用程序中禁用,因为它会停止 Javascript 的执行,从而提供糟糕的用户体验。出于开发目的,您应该使用 console.log,对于面向用户的交互,您应该使用基于 HTML 的对话框。

您可以创建自己的同步 alert/prompt,使用一个函数在完成之前等待 jQuery 承诺,然后在用户单击 "OK" 按钮时解决承诺。然后,当你用 "myCustomAlert" 替换你的 "alert" 时,你必须在调用之前将它调用的函数声明为 "async function" 然后 "await" 。

这听起来可能很复杂,但如果您在 JSFiddle 中使用它,它会非常简单。

如果您要移植的应用程序不能很容易地将功能分解为不同的部分,我发现这很有用。这确实需要 jQuery 库。

这是我的例子https://jsfiddle.net/littlej247/g4k2h56c/5/

//*****HTML*********

<button type="button" id="alertMe">Alert ME!</button>

<div id="backgroudDiv">  <!-- This is optional but I like to grey out the background -->
  <div id="alertDiv">
    <b><span id="alertTitle"></span></b>
    <br />
    <span id="alertText"></span>
    <hr>
    <button type="button" id="alertDone">OK</button>
  </div>
</div>

//Remember JS can't run in HTML files on chrome apps so functions are called by DOM
document.getElementById("alertMe").onclick = async function () {
  console.log("Starting function \n Processing a bunch of stuff, calculating variable(s)....");
  await myCustomAlert("Alert Title Here","Message");
  console.log("Continue processing stuff with the variable(s) after the alert is clicked.... \n function finished");
};


//*****JavaScript*********

//Alerts can not be used in chrome apps, myCustomAlert function is a replacement.
var alertPromise
function myCustomAlert(messageTitle,messageBody){ 
  console.log("myCustomAlert has been called");
  alertPromise = $.Deferred();

  document.getElementById("alertTitle").textContent=messageTitle;
  document.getElementById("alertText").textContent=messageBody;
  document.getElementById('backgroudDiv').style.display='block';

  return $.when(alertPromise).done();
}

document.getElementById("alertDone").onclick = function () {
  console.log("Finally, User clicked Done, \n now we can get back to work..");
  document.getElementById('backgroudDiv').style.display='none';
    alertPromise.resolve();
    return(false);
};

//*****Styles*********

#alertDiv { 
  width: 400px;
  padding: 15px;
  margin: 100px auto auto auto;
  z-index: 10000;
  background-color: lightblue;
  border-style: solid;
  border-color: black;
 }
#backgroudDiv { 
  display: none; 
  position: fixed; 
  z-index: 9000; 
  left: 0; 
  top: 0; 
  width: 100%; 
  height: 100%; 
  background-color: rgba(0,0,0,0.4); 
 }