javascript - 确定是否单击了 Google Chrome 打印预览中的打印/取消按钮

标签 javascript jquery html google-chrome printing-web-page

我一直在使用下面的代码打印我的页面:

window.print();

下图是 Google chrome 浏览器中打印预览的样子。它有两个主要按钮:printcancel

enter image description here

我想知道用户是否点击了printcancel 按钮。我所做的是使用 jquery:

打印预览的HTML代码:

<button class="print default" i18n-content="printButton">Print</button>
<button class="cancel" i18n-content="cancel">Cancel</button>

J查询代码:

 $('button > .cancel').click(function (e) {                
      alert('Cancel');
 });

 $('button > .print').click(function (e) {                
      alert('Print');
 });

我尝试了上面的代码,但没有成功。我错过了什么?

最佳答案

您无法直接从常规网页访问 Chrome 的内部窗口(在本例中为打印对话框)。

    (function () {

        var beforePrint = function () {
            alert('Functionality to run before printing.');
        };

        var afterPrint = function () {
            alert('Functionality to run after printing');
        };

        if (window.matchMedia) {
            var mediaQueryList = window.matchMedia('print');

            mediaQueryList.addListener(function (mql) {
                //alert($(mediaQueryList).html());
                if (mql.matches) {
                    beforePrint();
                } else {
                    afterPrint();
                }
            });
        }

        window.onbeforeprint = beforePrint;
        window.onafterprint = afterPrint;

    }());

或者,如果您想在打印预览打开时执行某些操作,您可以尝试以下操作:

$(document).bind("keyup keydown", function (e) {
         if (e.ctrlKey && e.keyCode == 80) {
             setTimeout(function () { CallAfterWindowLoad();}, 5000);
             return true;
         }
     });

    function CallAfterWindowLoad()
    {
        alert("Open and call");
    }

引用: How to capture the click event on the default print menu called by Javascript window.print()

也许如果您提供对这两个按钮单击事件的要求,我们可以为您提供替代解决方案。

关于javascript - 确定是否单击了 Google Chrome 打印预览中的打印/取消按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912933/

相关文章:

javascript - 删除脚本元素后脚本仍然运行

javascript - 如何使用 JQuery 将动态内容加载到 DIV 中

jQuery UI - 要包含哪些 CSS?

javascript - 使用 javascript 遍历 XML 节点

html - 手机横屏模式下div不调整

javascript - jQuery `prop` 在 FireFox 中无法在详细信息的 `open` 属性上工作

HTML 布局 float

javascript - LESS 浏览器编译器无法在第二台开发机器上运行

javascript - 当您使用 JavaScript 函数作为类时,它们是否仍然以自上而下的方式进行解析?

javascript - React JS - ESLint - 忽略具有 UNSAFE_componentWillMount、UNSAFE_componentWillUpdate 和 UNSAFE_componentWillReceiveProps 的组件的规则