当浏览器操作页面(popup.html)弹出时,我正在尝试从 chrome 扩展程序访问 twitter。因为是跨域访问,chrome-extension跨域访问好像只支持http,所以我使用Jsonp访问twitter api(https)。如果我直接在浏览器中打开 popup.html 效果很好,但它拒绝在 chrome 扩展中工作。
//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();
});
提前致谢。