Javascript Window.onload错误

时间:2017-05-05 13:50:35

标签: javascript

    window.open("link.html");
  window.onload = function(){  
   document.getElementsByClassName("whatever goes here.")[0].click();
  };

这是我上面的代码^,我要做的是让它当我打开一系列页面时它执行这个javascript命令“getElementsByClassName”,但是每当它因某种原因打开新页面时它就不会处理这个功能。

这是一个shopify商店。我需要打开一个新窗口并使用getElementsByClassName

1 个答案:

答案 0 :(得分:0)

首先,如果您尝试访问打开的页面中的元素,则需要引用使用对象引用打开的特定窗口。

为了能够在动态打开的选项卡/窗口上搜索元素并与之交互,必须从服务器请求页面(仅测试本地文件系统中的页面是不够的,您必须制作HTTP请求)即使你是,“Cross Origin Request Specification”限制也会发挥作用。

接下来,您的函数尝试在元素上调用手册click,这些元素没有为它们设置任何click()事件,因此不会发生任何事情。元素必须为它们建立事件处理程序(在它们所在的原始页面中或通过访问它们的页面)。

这是一个简单的示例,但请记住,它在Stack Overflow片段环境中不起作用。

// You must capture a reference to the new window that you are opening if you want to 
// work with the contents of it. Note that the full URL is necessary for this to work.
var newWindow = window.open("http://SameDomain.com/otherPage.html");

// Don't use onload, onclick, etc. to set up event handlers. That technique
// may "work", but it is out of date and limited in its functionality. Instead
// use the modern and standard .addEventListener() method.

// Now, you can access the specific window and interact with it as you normally would:
newWindow.addEventListener("DOMContentLoaded", function(){  

   // Now that the document is ready, you can access elements
   // within the page, but if you want something to happen when
   // they get clicked, you have to set that up.
   newWindow.document.getElementsByClassName("someClass")[0].addEventListener("click", function(e){
    alert("Hello from " + e.target.id);
   });
   
});
<!-- This code would be in the http://SameDomain.com/otherPage.html file. -->
<div class="someClass" id="div1">Click Me</div>
<div class="someClass" id="div2">You can't click me</div>