解决办法:使用 ifame 来实现。前提是要保证两个页面是同源的。
解决思路:在a页面中创建一个 ifame 标签,连接到 b 页面中。
下面是完整的实现代码
<body>
<div>a页面
<iframe id="myFrame" src="http://localhost:52330/b.html"></iframe>
<button onclick="printContent()">打印</button>
</div>
</body>
<script>
function printContent() {
var iframe = document.getElementById("myFrame");
var contentWindow = iframe.contentWindow || iframe.contentDocument;
console.log(contentWindow);
contentWindow.print();
}
</script>
注意如果出现这个报错,说明 a b 页面不同源,需要换一种解决方法。