Invoking javascript in iframe from parent page, IE

2019-08-08 10:26发布

问题:

This is a follow up to this question: Invoking javascript in iframe from parent page

I've implemented the answer provided by @Tomalak.

Here is a jsFiddle

The problem is this, the content in the iframe is dynamically created (so no cross domain issues). Within the content is a button whose onclick event handler calls window.print(). This prints only the content of the iframe(which is good and is serving as proof of concept).

Additionally, there is a button on the parent page which calls a public function published by the iframe. The function is printContent, and like the iframe button's onclick event handler, it also calls window.print().

This is the issue, when printing from the button on the parent page using IE 8, the content of the parent page also prints. (This does not happen with Chrome.)

Is there a fix which makes IE 8 print only the content of the iframe?

Interestingly enough, returning window.document.title via a public function, does return the title of the iframe content, even when using IE 8.

The fiddle demonstrates the problem and offers more detail.

回答1:

In IE you need to set focus to the window you want to print. This prints iframe when function is in parent page:

function printContent(){
    var el = document.getElementById('myFrame');
    el.contentWindow.focus();
    el.contentWindow.print();
    return;
}

If function is in the iframe, you can print it from anywhere:

function printContent(){
    window.focus();
    window.print();
    return;
}