要实现跨HTML页面调用JavaScript函数,可以采用以下几种方法:
(图片来源网络,侵删)
1、使用window.opener
对象
当一个HTML页面通过window.open()
方法打开另一个HTML页面时,被打开的页面可以通过window.opener
对象访问打开它的页面的JavaScript函数,有两个HTML页面:parent.html
和child.html
,在parent.html
中,我们通过window.open()
方法打开child.html
,然后在child.html
中调用parent.html
的JavaScript函数。
parent.html
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>Parent Page</title>
</head>
<body>
<h1>Parent Page</h1>
<button onclick="openChildPage()">Open Child Page</button>
<script>
function openChildPage() {
window.open('child.html', '_blank');
}
function showMessage() {
alert('Hello from parent page!');
}
</script>
</body>
</html>
child.html
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>Child Page</title>
</head>
<body>
<h1>Child Page</h1>
<button onclick="callParentFunction()">Call Parent Function</button>
<script>
function callParentFunction() {
window.opener.showMessage();
}
</script>
</body>
</html>
2、使用postMessage
和onmessage
事件
通过window.postMessage()
方法,我们可以在不同的HTML页面之间发送消息,接收方可以通过监听onmessage
事件来接收消息并执行相应的操作,有两个HTML页面:parent.html
和child.html
,在parent.html
中,我们通过window.open()
方法打开child.html
,然后在child.html
中通过postMessage
向parent.html
发送消息,parent.html
监听到消息后执行相应的JavaScript函数。
parent.html
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>Parent Page</title>
</head>
<body>
<h1>Parent Page</h1>
<button onclick="openChildPage()">Open Child Page</button>
<script>
function openChildPage() {
var childWindow = window.open('child.html', '_blank');
childWindow.addEventListener('message', function(event) {
if (event.origin === 'http://localhost') {
showMessage();
}
});
}
function showMessage() {
alert('Hello from parent page!');
}
</script>
</body>
</html>
child.html
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF8">
<meta name="viewport" content="width=devicewidth, initialscale=1.0">
<title>Child Page</title>
</head>
<body>
<h1>Child Page</h1>
<button onclick="sendMessageToParent()">Send Message to Parent</button>
<script>
function sendMessageToParent() {
window.opener.postMessage('callShowMessage', 'http://localhost');
}
</script>
</body>
</html>
以上就是两种跨HTML页面调用JavaScript函数的方法,在实际开发中,可以根据需求选择合适的方法来实现跨页面调用。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)