![](/img/trans.png)
[英]Why is same-origin-policy blocking this javascript call on a local domain?
[英]Is there a way in javascript to get all iframes that don't violate same-origin-policy with getElementsByTagName?
我正在编写一个 chrome 扩展,需要在页面上获取 html5 视频元素,但一些视频元素在 iframe 中。 我添加到我的 function 以搜索 iframe,但由于与具有不同 src 域的 iframe 相关的同源策略,我开始收到错误。
在我的 function 中,是否有一种简单的方法可以排除违反同源策略的 iframe? 或者更好(即使可能不可能),有没有办法仍然从主页搜索具有不同 src 域的 iframe?
有问题的 function:
function getVideo() {
var videos = document.getElementsByTagName("video");
if (videos.length >= 1) {
return videos[0];
}
var iframes = document.getElementsByTagName("iframe");
if (iframes.length >= 1) {
for (const frame of iframes) {
videos = frame.contentWindow.document.getElementsByTagName("video");
if (videos.length >= 1) {
return videos[0];
}
}
}
return null; // if a video doesn't exist
}
就在您认为您已经在这里搜索了足够长的时间以保证提出问题时,您会发现一些真正有用的东西。
根据这个问题的答案,我将我的代码更新为:
function getVideo() {
var videos = document.getElementsByTagName("video");
if (videos.length >= 1) {
return [videos[0], "main"];
}
// Code that will run only inside iframe
if (parent === top) {
var videos = document.getElementsByTagName("video");
if (videos.length >= 1) {
return [videos[0], "iframe"];
}
}
return [null, null]; // if a video doesn't exist
}
并将其包含在我的清单中,以便脚本也可以注入到 iframe 中:
"content_scripts": [{
"all_frames": true,
...
...
}],
这行得通,但它确实使我的其他功能非常难看。 例子:
// if a video exists, set it to the speed and give a notification
function setSpeed(newSpeed) {
var returnVal = getVideo();
var video = returnVal[0], type = returnVal[1];
if (video != null && type === "main") {
video.playbackRate = newSpeed;
inWindowAlert("Speed: " + newSpeed, 1000);
setIcon(newSpeed);
}
if (parent === top) {
if (video != null && type === "iframe") {
video.playbackRate = newSpeed;
inWindowAlert("Speed: " + newSpeed, 1000);
setIcon(newSpeed);
}
}
}
我会尝试提出一个更清洁的解决方案,但现在它可以工作。 希望这对任何人都有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.