2014-10-18 38 views
1

問題:是否可以檢測到在遠程站點上運行的js代碼是否從Chrome擴展的iframe中調用?我有一個遠程網站,當我被稱爲Chrome擴展程序時,想要覆蓋一些行爲,而是使用chrome.runtime.sendMessage和chrome.runtime.onMessageExternal將命令發送回擴展。檢測代碼是否從iframe中的遠程站點以Chrome擴展模式運行

在我popup.html我有這樣的:

<iframe src="http://localhost" width="100%" height="100%" frameborder="0"></iframe> 

在我的遠程站點(本地主機進行測試)在JS,我有這個:

$(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 
}); 

這是以任何方式可能嗎?我看了很多其他的文章和問題,談論我正在嘗試做什麼,但沒有把我設置在正確的軌道上。

謝謝!

回答

1

我解決了這個方式如下:

  1. 指向popup.html的iframe到localhost /索引擴展=鉻
  2. 添加以下的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 
    } 
    }); 
    
  3. 然後,在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擴展,同時仍然能夠修改某些行爲,以便它們變得更「擴展性」:-)。

這種整體方法當然不適用於所有場景,但它發生在爲我目前的項目工作。在其他情況下,您會從零開始創建擴展程序更好。

相關問題