【问题标题】:javascript open new tab and cannot get the tags and attributes from the new tab, but only get nulljavascript打开新标签,无法从新标签中获取标签和属性,但只能获取null
【发布时间】:2019-07-31 04:33:25
【问题描述】:

我是 Javascript 的新手。使用 javascript,我想使用 onload 方法打开一个新选项卡,并从新选项卡中获取所需的标签进行操作,但它不起作用。我该如何解决这个问题?

当我在任何谷歌搜索页面上时,我想打开http://google.com并通过Javascript自动在搜索框中插入一些文本。但它发出“Uncaught TypeError: Cannot set property 'value' of null”

我想看看父标签是否可以通过 console.log("") 访问 google.com 搜索框,但它显示我只是空。

从任何 google 搜索结果页面,我尝试在 google.com 搜索框中输入一些文本。

win = window.open("https://google.com/");

function searchbox() {
    win.document.querySelector('input.gLFyf.gsfi').value="aaaa";
};
win.onload = searchbox();

新的 google.com 标签页打开后,控制台结果是这样的,

Uncaught TypeError: Cannot set property 'value' of null
    at searchbox (<anonymous>:4:54)
    at <anonymous>:6:14
searchbox @ VM456:4
(anonymous) @ VM456:6

当我尝试这个时,

win = window.open("https://google.com/");

function searchbox() {
    console.log(win.document.querySelector('input.gLFyf.gsfi'));
};
win.onload = searchbox();

结果为空。

我不知道为什么它不起作用。

【问题讨论】:

    标签: javascript dom properties onload


    【解决方案1】:

    如果您使用window.open() 打开新打开的窗口,您将无法访问它的 DOM,除非它的 URL 与您的页面同源(所以 - 不是 Google ?)。

    这是来自window.open's documentation的引述:

    返回值

    一个 WindowProxy 对象,它基本上是 Window 的一个瘦包装器 代表新创建的窗口的对象,并具有其所有功能 可用的。如果无法打开窗口,则返回值为 而是为空。返回的引用可用于访问属性 新窗口的方法和方法只要符合 同源策略安全要求

    【讨论】:

    • 感谢您的回答。但我认为 google 搜索结果页面与 google.com 具有相同的源 URL,因为 google 搜索结果 URL 以 google.com/search?q=.... 开头。我是否缺乏相同 URL 来源的基本知识?
    • 您的代码在哪个 url 下运行?我怀疑你在 google.com 上运行它。
    • 我在任何 google 搜索结果页面上运行了 js 代码,例如 google.com/… 这是 abcd 结果页面
    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2015-04-25
    • 2012-11-18
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    相关资源
    最近更新 更多