问题
I'm beginner to learn JS and I am stuck with the following function.
I'm trying to open a new window and print in the console of the new window. My code is as follows:Can you please tell me where's the error ?
var newWindow = window.open("url");
newWindow.onload = function (newWindow) {
newWindow.console.log("...something...");
}
回答1:
After the code
var newWindow = window.open("url");
It should instantly open another window with "url" path. What happens after is field of work of "url" page. In this page you should have on document ready function which is similar to
newWindow.onload = function (newWindow) {
newWindow.console.log("...something...");
}
Which could be simple jQuery function
$( document ).ready(function() {
console.log( "ready!" );
});
回答2:
<html>
<script>
function myFunction() {
var myWindow = window.open("", "MsgWindow", "width=200, height=100");
myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>");
}
myFunction();
</script>
</html>
Write this code in a HTML file and run it, make sure pop-ups are not blocked.
回答3:
The result you want to get from the code is not possible. Let's call the window where you are executing javascript window 1
and you are opening a fresh new window window 2
. Now, window 2
neither has reference of your js code nor has the onload
event. onload event of window 2
is firing at window 1
instance. So, you are getting the console log at window 1
instance not in window 2
.
See the fiddle's console for window 1
instance.
回答4:
If you were to create a new window with the same domain (or no url), you can use the console just fine:
var newWindow = window.open("");
newWindow.console.log("test");
Example: https://jsfiddle.net/8p2fk4j0/ (disable popup blocking)
来源:https://stackoverflow.com/questions/34575107/trying-to-use-console-of-a-new-window