使用try块捕获'sameorigin'加载iframe时出错

Using try block to catch 'sameorigin' error when loading iframe

本文关键字:加载 iframe 出错 sameorigin try 使用      更新时间:2023-09-26

获得了一个脚本,从一个txt文件中获取url,并将它们一个接一个地放入iframe中。脚本如下:

 <script type="text/javascript">
           $.get("imones.txt", function (data) {
                var array = data.split(/'r'n|'r|'n/);
                var beforeLoad = (new Date()).getTime();
                var loadTimes = []; 
                    var beforeTimes = [];   
                $('#frame_id').on('load', function () {                                 
                    beforeTimes.push(beforeLoad);
                    loadTimes.push((new Date()).getTime()); 
                    $('#frame_id').attr('src', array.pop()); 
                        $.each(loadTimes, function (index, value) {
                            var result = (value - beforeTimes[index]) / 1000; 
                                if (result < 0) { 
                                    result = result * (-1);
                                }   
                            $("#loadingtime" + index).html(result);
                            beforeLoad = value;
                        });
                }).attr('src', array.pop());
            });
        </script>

我遇到了一个问题,当其中一个url有"同源"保护(例如google.com),我的问题是,它不会加载任何其他帧一旦它开始加载谷歌(它卡住了)。我被告知要尝试使用try catch块,但我不知道如何。我如何使用try catch来避免'同源'的url(请注意,我不希望他们加载,我希望他们跳过)。

我猜这里

<script type="text/javascript">
           $.get("imones.txt", function (data) {
                var array = data.split(/'r'n|'r|'n/);
                var beforeLoad = (new Date()).getTime();
                var loadTimes = []; 
                    var beforeTimes = [];   
                $('#frame_id').on('load', function () {                                 
                    beforeTimes.push(beforeLoad);
                    loadTimes.push((new Date()).getTime()); 
                    try {
                        $('#frame_id').attr('src', array.pop()); 
                        $.each(loadTimes, function (index, value) {
                            var result = (value - beforeTimes[index]) / 1000; 
                                if (result < 0) { 
                                    result = result * (-1);
                                }   
                            $("#loadingtime" + index).html(result);
                            beforeLoad = value;
                        });
                    } catch(ex) {}
                }).attr('src', array.pop());
            });
        </script>

这将包含您实际将url推入"src"属性的地方,从而触发请求。