2013-09-25 4 views
3

IE Tab 확장자를 사용하여 새 탭에서 Confluence에 저장된 Office 문서를 열려고 Chrome 확장 프로그램을 개발하려고합니다.Chrome 콘텐츠 스크립트를 사용하여 프로그래밍 방식으로 Confluence 페이지에 코드 삽입

'페이지 첨부보기'화면에 Office 첨부 파일에 대한 'Office에서 편집'링크가 있습니다. 링크에는 문서를 여는 데 사용되는 URLLauncher의 새 인스턴스를 만드는 클릭 이벤트가 있습니다. 이 기능은 Chrome에서 지원되지 않으므로 웹 페이지에 내 URLLauncher 프로토 타입을 추가하여 작동하도록하고 싶습니다. 한마디로

이 내 생각이다 :

  1. '보기 페이지 첨부 파일'페이지에 URLLauncher 프로토 타입을 주입 콘텐츠 스크립트와 크롬 확장 프로그램 (이것이 맞다면 나도 몰라 만들기 접근 방식, 그래서 나는 제안에 개방적이다).
  2. 사용자가 'Office에서 편집'링크를 클릭하면 URLLauncher.open 메서드는 IE 탭 확장 프로그램을 호출하여 첨부 파일을 새 탭에서 엽니 다.

'안녕하세요!' 웹 페이지를로드 할 때마다 경고하고, 이는 content.js가 주입되고 있음을 확인합니다. 그럼에도 불구하고 URLLauncher은 웹 페이지에서 사용할 수 없습니다. 컨텐츠 스크립트의 전역 window 개체가 페이지/확장 프로그램의 전역 네임 스페이스 (예 : window.URLLauncher은 정의되지 않음)와 구분되어 있기 때문입니다. 이 장애물을 극복하기 위해 어떻게 코드를 재구성 할 수 있습니까?

내 파일입니다

manifest.json을

{ 
    "manifest_version": 2, 
    "background": { 
     "scripts": [ 
     "background.js" 
     ] 
    }, 
    "content_scripts": [ { 
     "js": [ "content.js" ], 
     "matches": [ "<all_urls>" ] 
    } ], 
    "description": "This is a test extension", 
    "permissions": [ 
     "tabs", "http://*/*", "https://*/*" 
    ], 
    "name": "Test extension", 
    "version": "1.0.0" 
} 

background.js

chrome.tabs.executeScript(null, { 
    code: "document.body.appendChild(document.createElement('script')).src='" + 
    chrome.extension.getURL("content.js") + "';" 
}, null); 

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     console.log(sender.tab ? 
      "from a content script:" + sender.tab.url : 
      "from the extension"); 
     if (request.id == "doUrlLaunch") {   
     chrome.tabs.create({ url: request.nUrl, selected: true }); 
     sendResponse({result: "goodbye"}); 
     } 
    } 
); 

content.js

var prefixUrl = 'chrome-extension://hehijbfgiekmjfkfjpbkbammjbdenadd/iecontainer.html#url='; 
alert('Hi there!'); 
function URLLauncher() { 

} 

URLLauncher.prototype = { 
    open : function(urlStr) { 
     var newUrl = prefixUrl + 'https://host.com' + encodeURI(urlStr); 
     chrome.runtime.sendMessage({id: "doUrlLaunch", nUrl: newUrl}, function(response) { 
     }); 
    } 
} 

미리 감사드립니다. ;

UPDATE 1

은 내가 Rob W에 의해 주어진 지침이 page ('메시지 전달') 다음 파일을 편집 이제 코드가 페이지 자체에 삽입되지만 중요한 문제가 여전히 남아 있습니다. 실제 JS 코드는 콘텐츠 스크립트에 메시지를 보내지 만 메시지는 수신기에서 포착되지 않으므로 새 탭이 만들어지지 않고 콜백 함수가 응답을받지 못합니다. 내가 가진 오류 메시지 : (알 수 없음)에 대한 이벤트 처리기에서 오류가 발생했습니다. TypeError : 정의되지 않은의 'success'속성을 읽을 수 없습니다.

manifest.json을

{ 
    "manifest_version": 2, 
    "content_scripts": [ { 
     "js": [ "content.js" ], 
     "matches": [ "<all_urls>" ] 
    } ], 
    "web_accessible_resources": [ "script.js" ], 
    "description": "This is a test extension", 
    "permissions": [ 
     "tabs", "http://*/*", "https://*/*" 
    ], 
    "name": "Test extension", 
    "version": "1.0.0", 
    "externally_connectable": { 
     "ids": ["*"], 
     "matches": ["*://*.hostname.com/*"] 
    } 
} 

내용 :

업데이트 된 파일입니다.JS

var s = document.createElement('script'); 
s.src = chrome.extension.getURL("script.js"); 
s.onload = function() { 
    this.parentNode.removeChild(this); 
}; 
(document.head||document.documentElement).appendChild(s); 

chrome.runtime.onMessage.addListener(
//Unreachable code! 
    function(request, sender, sendResponse) { 
     console.log(sender.tab ? 
      "from a content script:" + sender.tab.url : 
      "from the extension"); 
     if (request.id == "doUrlLaunch") {   
     chrome.tabs.create({ url: request.nUrl, selected: true }); 
     sendResponse({result: "goodbye"}); 
     } 
    } 
); 

script.js

var prefixUrl = 'chrome-extension://hehijbfgiekmjfkfjpbkbammjbdenadd/iecontainer.html#url='; 
function URLLauncher() { 

} 

URLLauncher.prototype = { 
    open : function(urlStr) { 
     var newUrl = prefixUrl + 'https://hostname.com' + encodeURI(urlStr); 
     chrome.runtime.sendMessage({id: "doUrlLaunch", nUrl: newUrl}, function(response) { 
      if (!response.success) 
       console.log('Something went wrong...'); 
     }); 
    } 
} 
+1

가능한 중복 - A의 코드를 삽입 페이지를 콘텐츠 스크립트를 사용하여] (http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script) –

+0

당신의 도움에 감사드립니다 , Rob W. 내 코드를 업데이트했지만 삽입 된 코드가 메시지를 보낼 수없는 것 같습니다. 내가 위에서 자세히 설명한대로 내용 스크립트. 당신의 통찰력을 고맙게 생각합니다. –

+5

삽입 된 스크립트는 삽입 된 페이지에서 시작된 것처럼 작동합니다. 이러한 스크립트는 Chrome 확장 API를 사용할 수 없습니다. 배경 스크립트와 "이야기"를 나누려면 처음에는 내용 스크립트에 메시지를 보내야하며, 그러면 내용을 배경 페이지로 보냅니다. 삽입 된 스크립트에서 백그라운드로 메시지를 보내는 전체 예제는 http://stackoverflow.com/a/13779769/938089를 참조하십시오. 주입 스크립트와 콘텐츠 스크립트 간 통신에 대한 다른 예는 http://stackoverflow.com/a/10527809/938089를 참조하십시오. –

답변

0

여전히 대답에 관심이 있지만 청취자가 앉아 어디 편집 된 파일에 문제가있는 경우 확실하지.

  1. chrome.runtime.sendMessage 콘텐츠 스크립트에 도달하지 않습니다. 확장 페이지 용입니다. 콘텐츠 스크립트로 전달되는 메시지는 chrome.tabs.sendMessage을 통해 작동하지만이 작업과 관련이 없습니다.

  2. 콘텐츠 스크립트는 필요한 API 액세스가 없으므로 chrome.tabs을 호출 할 수 없습니다.

해결 방법은 해당 메시지를 수신하고 필요한 API를 호출 할 수있는 백그라운드 스크립트를 호출하는 것입니다. 따라서

, 당신은 content.js에서이 코드를 복용, 세 번째 스크립트가 필요합니다

// background.js 
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     console.log(sender.tab ? 
      "from a content script:" + sender.tab.url : 
      "from the extension"); 
     if (request.id == "doUrlLaunch") {   
     chrome.tabs.create({ url: request.nUrl, selected: true }); 
     sendResponse({result: "goodbye"}); 
     } 
    } 
);  

을 그리고 매니페스트 수정 : [A 크롬 확장 구축의

"background": { "scripts": [ "background.js" ] },