javascript - 修改将要打开的窗口

标签 javascript

我想在单击按钮时打开一个窗口,并修改将打开的页面的 html 和 css。我怎样才能做到这一点?

我在一个 symfony 项目上工作,我只想在将打开的窗口的一段上写字。为此我尝试了:

$( "#tom" ).click(function() { 
  var wind = window.open("{{ path('AjoutFournisseur') }}", "Ajouter un fournisseur", "width=520,height=1080");
  wind.document.getElementById("can").innerHTML='TEST'; 
});

我有这个错误:

Uncaught TypeError: Cannot set property 'innerHTML' of null at HTMLSpanElement. (add-volet:113) at HTMLSpanElement.dispatch (jquery.min.js:2) at HTMLSpanElement.y.handle (jquery.min.js:2)

最佳答案

如果弹出窗口与父窗口不在同一域中,则如果没有其他站点的合作,这是不可能实现的(CORS 规则和同源策略将适用)。

如果两个页面都在同一个域中,则您需要进行的更改是等待弹出窗口完成加载后再尝试修改;现在,您正在打开窗口,然后在网络请求有机会返回其内容之前立即尝试更改其内容。

我无法在正常运行的堆栈溢出代码片段中演示这一点,因为它不允许弹出窗口,但这就是它的样子:

$('#tom').on("click", function() {
  let thePopup = window.open("url_of_popup_window.html");
  thePopup.onload = function(e) {
    thePopup.document.getElementById("can").innerHTML = 'TEST';
    // Or, since you're already using jQuery, use this equivalent to the above line:
    // $('#can', e.target).html('TEST'); // e.target is the popup document here
    // (this would be usable even if jQuery is not in the popup window, because this script runs in the parent)
  }
});

关于javascript - 修改将要打开的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480670/

相关文章:

javascript - 在 Backbone.history 中读取以前的 URL

javascript - 阅读 Facebook 个人页面帖子

javascript - 如何删除 iFrame 中的某个元素

javascript - 将Class 添加到链接中指定的元素的动态代码

javascript - 如何将 promise 的 XHR 转换为 async/await?

javascript - 离开页面时将 url 从 HTTPS 更改为 HTTP javascript

javascript - 如果整个 DOM 使用相同的 div,则仅将字符串附加到特定的 div 一次

javascript - 动态 jQuery 内容加载

javascript - 如何将底部 div 保持在顶部 div 下方的恒定高度,并且它们之间有一个 div?

javascript - 图像加载错误