Vue監(jiān)聽iframe加載失敗事件的三種實現(xiàn)方法
在vue項目中要監(jiān)聽 iframe 加載失敗的事件,可以使用以下幾種方法:
方法一:使用onerror事件(同源)
給iframe添加一個error事件監(jiān)聽器,當iframe加載失?。ňW(wǎng)絡問題、資源不存在、404錯誤)時這個事件會被觸發(fā)。(不適用于跨域請求)
<template>
<iframe ref="iframeRef" @error="handleError"></iframe>
</template>
<script setup>
import { ref } from 'vue';
const iframeRef = ref(null);
const handleError = (event) => {
console.log('iframe加載出錯', event);
// 你可以在這里檢查錯誤狀態(tài)碼
if (event.target.contentWindow.document.readyState === 'complete' && event.target.src !== '') {
console.log('可能是404錯誤');
}
};
</script>
方法二:使用load事件結合內(nèi)容檢查(同源)
使用load事件,并在事件觸發(fā)后檢查頁面內(nèi)容是否表明了404錯誤。此方法適用于同源情況下,如果iframe加載的是不同源的頁面,由于瀏覽器安全限制,你將無法訪問iframe內(nèi)部的contentDocument或contentWindow屬性。
<template>
<iframe ref="iframeRef" @load="handleLoad"></iframe>
</template>
<script setup>
import { ref } from 'vue';
const iframeRef = ref(null);
const handleLoad = () => {
const iframeContent = iframeRef.value.contentDocument || iframeRef.value.contentWindow.document;
if (iframeContent) {
const statusText = iframeContent.title || iframeContent.documentElement.textContent;
if (statusText.includes('404')) {
console.log('檢測到404錯誤');
}
}
};
</script>
方法三:使用XMLHttpRequest或fetch API預檢查URL狀態(tài)(非同源/同源均可)
注釋:在將URL設置到iframe之前,你可以使用XMLHttpRequest或fetch API預檢查URL是否返回200狀態(tài)碼或其他預期的響應。如果狀態(tài)碼不是預期的,你可以決定不加載該URL到iframe或者顯示一個錯誤消息。
<template>
<iframe ref="iframeRef"></iframe>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { checkUrl } from './utils'; // 假設你的檢查函數(shù)在utils.js文件中定義
const iframeRef = ref(null);
const url = 'http://example.com/some-page'; // 你的目標URL
async function checkUrl(url) {
try {
const response = await fetch(url);
if (!response.ok) { // 檢查狀態(tài)碼是否表明了錯誤(例如404)
throw new Error('URL返回了非200狀態(tài)碼');
}
return true; // URL有效,可以繼續(xù)加載到iframe中
} catch (error) {
console.error('URL檢查失敗:', error);
return false; // URL無效或無法訪問,不加載到iframe中或顯示錯誤信息
}
}
onMounted(async () => {
if (await checkUrl(url)) {
iframeRef.value.src = url; // URL有效,設置iframe的src屬性
} else {
console.log('無法加載URL,可能是404錯誤'); // URL無效,處理錯誤情況,例如顯示錯誤消息等。
}
});
</script>
非同源推薦使用方法三,可以根據(jù)實際需求添加缺省提示!
到此這篇關于Vue監(jiān)聽iframe加載失敗事件的幾種實現(xiàn)方法的文章就介紹到這了,更多相關Vue監(jiān)聽iframe加載失敗內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3 setup點擊跳轉(zhuǎn)頁面的實現(xiàn)示例
本文主要介紹了vue3 setup點擊跳轉(zhuǎn)頁面的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-10-10
Vue中transition單個節(jié)點過渡與transition-group列表過渡全過程
這篇文章主要介紹了Vue中transition單個節(jié)點過渡與transition-group列表過渡全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
在vue中使用express-mock搭建mock服務的方法
這篇文章主要介紹了在vue中使用express-mock搭建mock服務的方法,文中給大家提到了在vue-test-utils 中 mock 全局對象的相關知識 ,需要的朋友可以參考下2018-11-11
關于對keep-alive的理解,使用場景以及存在的問題解讀
這篇文章主要介紹了關于對keep-alive的理解,使用場景以及存在的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

