问题:是否可以检测是否在Chrome扩展程序的iframe中调用远程站点上运行的js代码?我有一个远程网站,我称之为Chrome扩展程序时,想要覆盖一些行为,而是使用chrome.runtime.sendMessage和chrome.runtime.onMessageExternal将命令发送回扩展程序。
在我的popup.html中,我有这个:
<iframe src="http://localhost" width="100%" height="100%" frameborder="0"></iframe>
在我的远程站点上的js(localhost for testing)中,我有这个:
$(document).ready(function () {
if (someHowCheckIfIAmBeingCalledFromAChromeExtension == true) { //what do I put here?
{
// The ID of the extension we want to talk to.
var extensionId = "abc";
// Make a simple request:
chrome.runtime.sendMessage(extensionId, { message: "connected!" },
function (response) {
if (!response.success)
handleError(message);
});
}
}
});
在我的popup.js中我有:
chrome.runtime.onMessageExternal.addListener(
function (request, sender, sendResponse) {
//do something with request.message
});
这有可能吗?我已经看了很多其他的文章和问题,有点谈论我想要做的事情,但没有让我在正确的轨道上完全正确。
谢谢!
答案 0 :(得分:1)
我通过以下方式解决了这个问题:
在remote / localhost站点上添加了以下jquery索引:
$(document).ready(function () {
//check if query string is present
if (getParameterByName('extension') == 'chrome')
{
var extensionId = "abc";
//append the query string of each link on the page to make sure the site stays in "extension mode"
$('a').each(function () {
var _href = $(this).attr('href');
var _newHref;
if (_href.indexOf('?') >= 0) {
_newHref = _href + '&extension=chrome';
} else {
_newHref = _href + '?extension=chrome';
}
$(this).attr("href", _newHref);
});
//after this line I catch/change/override any behavior I want to change when the site is used form within the extension
//Then, I use chrome.runtime.sendMessage to send any custom commands to the extension
}
});
然后,在popup.js中,我必须遵循:
chrome.runtime.onMessageExternal.addListener(
function (request, sender, sendResponse) {
//do something with the caught behavior
});
//If you want to make the website snap out of "extension mode",
//clean all urls with this function when forwarding urls/opening tabs from the extension.
//The website will then function as usual, stripped of all the extension specific behaviour.
function cleanChromeExtensionQueryString(url)
{
var cleaned;
if (url.indexOf('?extension=chrome') >= 0) {
cleaned = url.replace('?extension=chrome', '');
}
else if (url.indexOf('&extension=chrome') >= 0) {
cleaned = url.replace('&extension=chrome', '');
};
return cleaned;
}
此方法允许我将响应式网站重新用作Chrome扩展程序,同时仍然可以修改某些行为,以便它们变得更加“扩展” - #34; : - 。)
这种整体方法当然不适用于所有场景,但它适用于我当前的项目。在其他情况下,您最好从头开始创建扩展程序。