Reputation: 1767
I try to pass *auth_token* to my Chrome extention for use it in GET requests further.
I think it's good if
How to realize paragraph 4? thank you
Upvotes: 2
Views: 505
Reputation: 116020
The Chrome documentation on content script communication recommends using window.postMessage
in the sending code (here, the web page) and using window.addEventListener("message", ...)
in the listening code (here, the content script of the Chrome extension, injected into the page). Technically, any kind of custom DOM event could also do this, but postMessage
/message
already has built-in support.
You should be able to lift the example code from the codes nearly verbatim:
Native web page:
// right after we get auth_token saved to a variable...
window.postMessage({ auth_token: auth_token }, "http://www.mypagedomain.com");
(Make sure http://www.mypagedomain.com
is changed to your actual protocol/domain.)
contentscript.js (in Chrome extension, listening)
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);
From inside the event listener, you could use message passing to pass the auth_token
to your background page, if necessary.
EDIT:
Your manifest should include something like this (note the use of run_at
below to inject the script before the page loads):
...
"content_scripts": [
{
"matches": ["http://www.mypagedomain.com/*"],
"js": ["contentscript.js"],
"run_at": "document_start"
}
],
...
Upvotes: 0
Reputation: 1767
Good to apsillers
yes, finally, i GET it! in my contentscript.js (which load in my token-page) get the token and send it to background
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;
});
Upvotes: 1
Reputation: 13441
I think localStorage
of page could act as a brigde between pages and extension.
At stage 3 where the auth_token created, dump it to localStorage
,
<script type="text/javascript">
...
var auth_token = "sfafsafasfsaf";
localStorage["auth_token"] = auth_token;
...
</script>
And get the auth_token in content script (content.js),
console.log(localStorage["auth_token"])
Upvotes: 0