2012-12-03 18 views
2

我尝试将* auth_token *传递给我的Chrome扩展,以便进一步在GET请求中使用它。如何将数据从网页传递到chrome ext?

我认为这是一件好事,如果

  1. 我们试图从$不用彷徨获得用户( 'APP /得/用户'{AUTH_TOKEN: ''}, 回调)在我的Chrome extention]
  2. 如果我们得到了'not_auth的回应,在新标签页回调开放auth_page [在我的Chrome extention]
  3. 我们登录并重定向到页面,在那里产生* AUTH_TOKEN * [我的WEB-APP-PAGE]
  4. 将* auth_token *传递给我的Chrome扩展程序?????怎么样?通过JS? [在我的WEB-APP-PAGE]

如何实现第4段?谢谢

+1

请参阅Google关于[内容脚本通信]的文档(http://developer.chrome.com/extensions/content_scripts.html#host-page-communication)。内容脚本和网页共享DOM,因此在内容脚本或网页中触发的DOM事件对两者都是可见的。 – apsillers

回答

0

我觉得localStorage的页面可以充当页面和扩展之间的brigde。

在第3阶段,其中AUTH_TOKEN创建,它转储到localStorage

<script type="text/javascript"> 
... 
var auth_token = "sfafsafasfsaf"; 
localStorage["auth_token"] = auth_token; 
... 
</script> 

而且在content script得到的auth_token(content.js),

console.log(localStorage["auth_token"]) 
+1

不,页面的localStorage和ext的localStorage是隔离的。 console.log(localStorage [“auth_token”])print undefined – Luciuz

+0

@Luciuz,抱歉,但你错了,我试过这个工作。您可以获取包含content.js的当前页面的localStorage数据。但不要忘记,它必须**内容脚本** – ocanal

0

Chrome浏览文档上content script communication建议在发送代码(这里是网页)中使用window.postMessage,并在侦听代码中使用window.addEventListener("message", ...)(这里,内容sc Chrome扩展的注入,注入页面)。从技术上讲,任何一种自定义DOM事件也可以做到这一点,但postMessage/message已经有内置的支持。

你应该能够解除从代码示例代码几乎一字不差:

本地网页:

// right after we get auth_token saved to a variable... 
window.postMessage({ auth_token: auth_token }, "http://www.mypagedomain.com"); 

(确保http://www.mypagedomain.com更改为您的实际协议/域) (在Chrome扩展中,收听)

window.addEventListener("message", function(event) { 
    // We only accept messages from ourselves 
    if (event.source != window) { 
     return; 
    } 

    console.log("auth_token received: " + event.data.auth_token); 
}, false); 

从事件监听器中,如果需要,可以使用message passingauth_token传递到您的背景页面。

编辑:

你的清单应包括这样的事情(注意使用以下run_at页面加载前注入脚本):

... 
"content_scripts": [ 
    { 
    "matches": ["http://www.mypagedomain.com/*"], 
    "js": ["contentscript.js"], 
    "run_at": "document_start" 
    } 
], 
... 
+0

谢谢你的答案,但我不能发送(或获取)document.ready消息。 $(function(){window.postMessage({...});})不起作用。但在页面加载后window.postMessage({...});效果很好 – Luciuz

+0

apsillers,你知道为什么window.addEventListener“工作”只有contentscript.js和不背景background.js? – Luciuz

+0

@Luciuz我在我的答案中添加了一个样本''run_at“:”document_start“'',它会在'$(document).ready'之前注入脚本。 – apsillers

1

好于apsillers

是的,最后,我得到它! 在我contentscript.js(其中负荷在我的令牌页)获得令牌,并将其发送到后台

contentscript.js

$(function(){ 
    //get token from page 
    var token = $.getUrlVar('token'); 
    if (typeof token != 'undefined') { 
    chrome.extension.sendMessage({token: token}); 
    } 
}); 

background.js

/*button handler*/ 
function main_click() { 
    alert(localStorage['auth_token']); 
} 
chrome.browserAction.onClicked.addListener(main_click); 


/*listener*/ 
chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) { 
    if (request.token) 
     localStorage['auth_token'] = request.token; 
    }); 
相关问题