-1

Suppose I have design a chrome extension which have four mode,then I choose one mode to change the page's content script and the page changed.But if I enter another page,this mode does not work.I put my set about the mode in popup page'javascript. What I hope is when I enter other pages,the mode also works.And if I closed the chrome software, then open it again, the extension can be the mode I choosed before? Can this be worked out? My code is here. popup.js

var colorMode = 0;
var temp = 0;
var flag = 1;
function transUp(){

if (flag){
    flag = 0;
}
else{
    colorMode = temp + 1;
    if(colorMode == 6) colorMode = 0;
}
chrome.tabs.executeScript(null, {code:"colorChange('" + colorMode + "')"}); 
temp = colorMode;
colorMode++;
if(colorMode == 6) colorMode = 0;
}


document.addEventListener('DOMContentLoaded', function () {
document.getElementById("up").addEventListener('click',transUp);
});
popup.html

<!doctype html>
<html>
  <head>
    <title>Set Page Color Popup</title>
    <style>
    *{
        margin: 0;
        padding: :0;
    } 
    .container{
        overflow:hidden;
        width:74px;
        height:74px;
        margin:10px;
    }
    #up{
        background: url(up.png) center no-repeat;
        background-size: 28px 28px;
        margin: 3px 0 0 3px;
    }
    #up:hover{
        box-shadow: 0 0 5px #000;
    }

    div div{
        width: 32px;
        height: 32px;
        border: 1px #000 solid;
        float: left;
        cursor: pointer;
    }

    </style>
    <script src="popup.js"></script>
  </head>
  <body>
    <div class="container">
        <div id="up"></div>
    </div>
  </body>
</html>

contentscript.js

var colorFont=['#fff','#feff00','#fff','#feff00','#fff','#fff'];
var colorBack=['#000','#000','#0000bf','#0000bf','#00ff00','#ff0000'];
var colorNum = 0;
function colorChange(color){
    colorNum = color;
    doTrans(colorNum);
}
function doTrans(colorKey){
    var tags = document.body.getElementsByTagName('*');
    for ( var i = 0; i < tags.length; i++)
    {
        tags[i].style.color=colorFont[colorKey];
        tags[i].style.backgroundColor=colorBack[colorKey];
    }
}
yovino
  • 3
  • 1

1 Answers1

0

You should use persistent storage available to both your popup and the content script.

Chrome provides that in the form of chrome.storage API.

Google's documentation on Options pages provides a nice example.

Be mindful that chrome.storage is asynchronous. Don't make common mistakes.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206