在background.js,我注射了一个iframe
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.action == "doubanSearch")
test(request.title, request.year);
}
);
function test(title, year){
var frame = document.createElement('iframe');
frame.src = 'https://movie.douban.com/subject_search?cat=1002&search_text=' + title + ' '+ year;
document.body.appendChild(frame);
}但是,一旦加载了iframe,background.js就不再响应doubanSearch请求。是否有一种解决方案可以让background.js保持对未来请求的响应,即使加载了iframe?
我已经单独检查了content.js,并可以确认它做了我希望它做的事情。
更新1
发出请求的netflixContent.js:
var prevDOM = null;
var prevMovieTitle = 'prevMovie';
// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
var srcElement = e.srcElement;
if (srcElement == null)
return;
if (prevDOM != srcElement){
prevDOM = srcElement;
return;
}
// find the bob-overlay class
if (srcElement.parentElement != null && srcElement.parentElement.className.startsWith('bob')) {
while (srcElement.className!="bob-overlay"){
srcElement = srcElement.parentElement;
// if srcElement is no longer a bob- class, we are out of luck here.
if (srcElement == null || !srcElement.className.startsWith('bob'))
return;
}
}
// the srcElement at this stage has to be bob-overlay class!
if (srcElement == null || srcElement.className!="bob-overlay")
return;
// now we are in the right place, get movie title and publication year
var movieTitle = srcElement.getElementsByClassName('bob-title');
var movieYear = srcElement.getElementsByClassName('year');
if (movieTitle.length != 1){
console.log('Movie title not found.', srcElement);
return;
}
if (movieYear.length != 1){
console.log('Movie year not found.', srcElement);
return;
}
// now get the title and year
movieTitle = movieTitle[0].textContent;
movieYear = movieYear[0].textContent.trim();
// if the current movie is the same as the previous movie, we return.
if (movieTitle == prevMovieTitle)
return;
// return if title is empty
if (movieTitle == '')
return;
// if movie year isn't empty, add parenthesis.
if (movieYear != '')
movieYear = '(' + movieYear + ')';
prevMovieTitle = movieTitle;
console.log('Movie found:', movieTitle, movieYear);
// replace special characters with space.
movieTitle = movieTitle.replace(/[^\w\s]/g, ' ').trim();
console.log('Movie found (special characters removed) :', movieTitle, movieYear);
// now let's send the message and start searching!
chrome.runtime.sendMessage({action: 'doubanSearch', title: movieTitle, year: movieYear});
}, false);它是托管在github上的开源资源,以防您需要检查整个代码。我对js和chrome扩展开发非常陌生,所以请原谅我的糟糕编码:)。
更新2
发送请求之前的背景页:

发送请求并加载iframe之后的背景页。

此外,后台页面链接不再可以从chrome://extensions中获得:

发布于 2018-03-07 15:51:01
站点执行破坏帧的操作(将top.location分配给页面本身的URL ),将后台页面导航到站点URL,这样扩展就不再有后台页面了。它看起来像是Chrome中的一个疏忽,在最近的一些版本中它被断断续续地阻止了,并且即将在v67中永久修复。
解决方案是通过添加以下属性来对iframe进行沙箱化:
frame.sandbox = 'allow-scripts';有些站点可能需要更多的特性,例如allow-forms,完整列表见MDN。
https://stackoverflow.com/questions/49143179
复制相似问题