skip to Main Content

is there a way in javascript to open a link in a new page and append on this page a div?
Lets suppose that I have page1.html which contains a div with a link and two radio buttons "yes" and "no" I want to open the link in another page and put on this page the div with the radio button over the content of the second page.

For the moment I use this example code but it does not work

// open the URL in a new window
var win = window.open("https://www.google.com/", "_blank");

win.addEventListener("load", function() {
    var n = "<div><h1>Hello from the new window!</h1></div>";
    win.document.body.innerHTML = n;
});

the URL can be anything and it is not on the same domain of the first page

2

Answers


  1. The short answer is no for pages that are not in the same domain as the parent page. That would be an invitation for malware to masquerade as a search agent and then intercept any interactions with pages opened from the parent page.

    Login or Signup to reply.
  2. If you want to open a link in a new window that is not on the same domain as the current page and also modify its content, you can

    1. Create a new HTML page that contains the elements you want to display.
    let html = '<html><head><title>New Page</title></head>'
    html += '<body><div><h1>Hello from the new window!</h1>'
    html += '<input type="radio" name="option" value="yes">Yes'
    html += '<input type="radio" name="option" value="no">No</div></body></html>';
    
    
    1. Encode the HTML content as a data URI
    const dataUri = `data:text/html;charset=UTF-8,${encodeURIComponent(html)}`;
    
    
    1. Pass it as query parameter to the URL you want to open and open it in a new window
    const win = window.open(`https://www.example.com/?page=${dataUri}`, '_blank');
    
    
    1. On the target page, check for the page query parameter in the URL and if it exists, parse the HTML content and append it to the body of the page.
    const params = new URLSearchParams(window.location.search);
    const page = params.get('page');
    
    if (page) {
      const html = decodeURIComponent(page.replace(/^data:text/html;charset=UTF-8,/, ''));
      const div = document.createElement('div');
    
      div.innerHTML = html;
      document.body.appendChild(div);
    }
    
    

    This approach works because the HTML content is not actually being modified on the target page, but rather it is being passed as a parameter to the page. Doing this without interacting with the other page involves additional server-side code or browser extensions. But keep in mind this can be a security risk and can also violate the terms of service of the website.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search