Search code examples
javascriptgoogle-chromebookmarklet

Ask for input then open in new window


I don't know much JavaScript so I was just wondering if it would be possible for a Java alert to pop up asking for a URL and then set the iframe arc to the URL (this will run as a bookmarklet).

Basically, I am looking for a prompt to pop up asking for a url and then open a new window and create an iframe in the new window with the arc that was typed earlier l.

javascript:

    var win = window.open();
    win.document.write('<style>body {margin: 0;}</style>
                       <iframe width="100%" height="100%" src="//bing.com" frameborder="0" 
                       sandbox="allow-forms allow-pointer-lock allow-same-origin allow-scripts">
                       </iframe>');

Thank's in advance!


Solution

  • Yes it's possible, you can use a self calling function to enclose the script:

    javascript: (function() {
    var alertWinRes  =  prompt("Please enter Site", "bing.com");
    if(alertWinRes !== null){
       var win = window.open("My new Window"); 
       win.document.write('<style>body {margin: 0;} 
       </style><iframe width="100%" height="100%" src="//' + alertWinRes + 
       '" frameborder="0" sandbox="allow-forms                        
       allow-pointer-lock allow-same-origin allow-scripts"></iframe>');     
     }
    })();
    

    The same functionality can be achieved without iframe:

    javascript: (function() {
    var alertWinRes  =  prompt("Please enter Site", "bing.com");
    if(alertWinRes !== null){
       var win = window.open("https://" + alertWinRes, "_blank");     
    }
    })();
    

    Using prompt creates an alert the user can use to enter the text and the second parameter is used to set a default. You'll have to have website already open for this to trigger, for security reasons in a new tab it doesn't work (there's work arounds posted online about it if needed).