2013-08-06 2 views
0

브라우저 동작 페이지 (popup.html) 팝업이 표시되면 크롬 확장 프로그램에서 트위터에 액세스하려고합니다. 도메인 간 액세스 및 크롬 확장 교차 도메인 액세스는 HTTP 만 지원하므로 Jsonp를 사용하여 Twitter API (https)에 액세스합니다. 브라우저에서 직접 popup.html을 열면 제대로 작동하지만 크롬 확장 프로그램에서는 작동하지 않습니다.브라우저 액션 페이지에 스크립트 요소를 삽입 할 수 없습니다.

//manifest.json

"permissions": [ 
    "tabs", "http://*/*", "https://*/*" ,"unlimitedStorage" 
] 

//popup.html

<html> 
<head> 
    <meta charset="utf-8"> 
    <script src="../js/jquery.min.js"></script> 
    <script src="../oauth/oauth.js"></script> 
    <script src="../oauth/sha1.js"></script> 
    <script src="../js/popup.js"></script> 
    </head> 
    <body> 
    ... 
    </body> 
</html> 

//popup.js

function mycallback(json) 
{ 
    alert("callback"); //never get called in chrome extension 
} 

function getTwitter() 
{ 
    var url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; 


    var accessor = { 
     token: "...", 
     tokenSecret: "...", 
     consumerKey : "...", 
     consumerSecret: "..." 
    }; 


    var message = { 
     action: url, 
     method: "GET", 
     parameters: { 
        "callback":"mycallback", 
        "include_entities":true, 
        "include_rts":true, 
        "user_id":"...", 
        "count":1 
        } 
    }; 

    OAuth.completeRequest(message, accessor); 
    OAuth.SignatureMethod.sign(message, accessor); 
    url = url + '?' + OAuth.formEncode(message.parameters); 

    // Create a new script element 
    var script_element = document.createElement('script'); 

    // Set its source to the JSONP API 
    script_element.setAttribute('type', 'text/javascript'); 
    script_element.setAttribute('id', 'script_element'); 
    script_element.setAttribute('src', url); 
    if(!document.getElementById('script_element')) 
     document.getElementsByTagName('head')[0].appendChild(script_element); 
} 



$(document).ready(function(){ 
    getTwitter(); 
}); 

미리 감사드립니다.

답변

1

CSP로 인해 코드가 작동하지 않습니다. popup.html을 디버그하는 방법은 this answer을 참조하십시오.

가장 좋은 해결책은 크롬 확장 프로그램에서 JSONP를 사용하지 않는 것입니다

하지만 XMLHttpRequest :

이 메시지에서 callback 키를 제거하고 당신이 "얻을 구문 에러 경우

var xhr = new XMLHttpRequest(); 
xhr.open('GET', url); 
xhr.onload = function() { 
    mycallback(JSON.parse(xhr.responseText)); 
}; 
xhr.send(); 

var script_element = .... 교체 : 예기치 않은 토큰 m "을 선택했다면 메시지에서 callback 키를 제거했는지 확인하십시오. 그렇지 않으면 트위터의 API는 여전히 JSONP 형식의 응답으로 응답합니다.

여전히 어떤 이유로 JSONP를 사용하려면, 그리고 웹 서비스가 HTTPS에서 호스팅되는 경우 : 계획, 당신은 당신의 manifest.json에 다음 필드를 추가하여, 또한 relax the CSP을 할 수 있습니다

"content_security_policy": "script-src 'self' https://api.twitter.com; object-src 'self'" 
+0

쿨! 작동, 감사합니다 백만! – camino

관련 문제