Search code examples
javascriptbookmarkletpopulate

Is it possible to create a blank page with 'pre-populated' code inside?


I'm trying to create a bookmarklet which can be clicked to open a new 'blank page' using about:blank or similar.

Here's the rub. The new blank page needs to have source code inside of it. specifically it needs to have javascript inside of it which waits for the new blank page to finish loading/instantiating (whichever is relevant), and then displays an alert box reading 'success!' or similar.

So far everything I have tried has caused the alert to be displayed in the current tab at the same time the new blank page is created in a different tab... or else it has cause the new blank page tab to instantiate only after the alert box has been displayed and addressed in the current tab.

Here is what I've tried.

javascript:
window.open('about:blank'); window.alert('success');

javascript:
var a = window.alert('success');
var b = window.open('about:blank', '', '_blank');
b.document.write(a);

Solution

  • You can try this:

      window.open('data:text/html,<!DOCTYPE html><script>alert("success");</script><body><h1>Hello World!</h1></body>', 'myTab');
    

    For some reason the above code does not work in Chrome. In this case you can use this:

    var page = window.open();
    page.document.open();
    page.document.write('<html><div>Mert</div></html>');
    page.document.close();