gpt4 book ai didi

javascript - 如何调用另一个网页上的js函数?

转载 作者:行者123 更新时间:2023-12-02 17:07:40 26 4
gpt4 key购买 nike

我想在另一个网页上调用 JavaScript 函数。到目前为止,我的解决方案是创建一个带有包含目标页面的 iframe 的页面。

<a onclick="func1()">Call</a>
<script type="text/javascript">
function func1()
{
document.getElementById('myFrame').contentWindow.some_function();
}
</script>
<iframe id="myFrame" src="http://www.webpage.com">

问题是,此解决方案仅在两个页面具有相同域时才有效。否则,我会收到此错误:

Uncaught SecurityError: Blocked a frame with origin "http://my_webpage.com" from accessing a frame with origin "http://not_my_webpage.com". Protocols, domains, and ports must match. 

我在谷歌上搜索了几个小时,但我只发现我需要使用

document.domain = document.domain;

使用后,我收到此错误:

Uncaught SecurityError: Blocked a frame with origin "http://my_webpage.com" from accessing a frame with origin "http://not_my_webpage.com". The frame requesting access set "document.domain" to "http://my_webpage.com", but the frame being accessed did not. Both must set "document.domain" to the same value to allow access. 

我想我需要在两个页面上使用它,但 iframe 中的页面不是我的,我无权访问它。有任何想法吗?谢谢。

最佳答案

你就是做不到。想象一下,如果这种事情是可能的……这将是一个巨大的安全缺陷。这是因为您无法访问具有另一个来源的框架,浏览器会自动阻止每个尝试访问具有不同来源的窗口的脚本。

关于javascript - 如何调用另一个网页上的js函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25104334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com