Javascript 检测代码是否作为Chrome扩展在iframe中从远程站点运行
问题:是否有可能检测到远程站点上运行的js代码是否正在从Chrome扩展的iframe中调用?我有一个远程网站,当被称为Chrome扩展时,我希望覆盖一些行为,而是使用Chrome.runtime.sendMessage和Chrome.runtime.onMessageExternal将命令发送回扩展 在我的popup.html中,我有以下内容:Javascript 检测代码是否作为Chrome扩展在iframe中从远程站点运行,javascript,jquery,google-chrome-extension,Javascript,Jquery,Google Chrome Extension,问题:是否有可能检测到远程站点上运行的js代码是否正在从Chrome扩展的iframe中调用?我有一个远程网站,当被称为Chrome扩展时,我希望覆盖一些行为,而是使用Chrome.runtime.sendMessage和Chrome.runtime.onMessageExternal将命令发送回扩展 在我的popup.html中,我有以下内容: <iframe src="http://localhost" width="100%" height="100%" frameborder="0
<iframe src="http://localhost" width="100%" height="100%" frameborder="0"></iframe>
$(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
});
这有没有可能?我看过很多其他的文章和问题,这些文章和问题有点像是在谈论我正在尝试做什么,但没有让我走上正确的轨道
谢谢 我用以下方法解决了这个问题:
$(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
}
});
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;
}