2017-01-03 59 views
-2

如果我使用JS创建一个新窗口/ tweet分享,我是否也可以从本地存储中获取信息?是否可以将本地存储值加载到推文中?

<li class="fa fa-twitter" onclick="window.open('https://twitter.com/intent/tweet?text=I just score X on this game!', 'newwindow', 'width=300, height=250')"></li> 

我们目前存储用户在localStorage的得分与score值。我们甚至在页面上打印它。会不会把它上传到推文中?

到目前为止,我已经尝试使用跨度,并追加得分,但是这打破了URL。

任何想法?

+0

什么是破损的URL的样子?注入字符串可能会导致一些URL转义问题 –

回答

3

您可以添加值使用串联:

<li class="fa fa-twitter" onclick="window.open('https://twitter.com/intent/tweet?text=I just score ' + localStorage['score'] + ' on this game!', 'newwindow', 'width=300, height=250')"></li> 
+0

对不起,试图接受这个,但后来它说SO因维护而停机。这解决了我的问题!非常感谢! –

0

内联JS是可怕:)

试试这个

<li class="fa fa-twitter" onclick="onClick"></li> 

function onClick(){ 
    var val = localStorage.get('something'); 
    window.open("https://twitter.com/intent/tweet?text=I just score X on this"+val+" game!', 
    'newwindow', 
    'width=300,height=250') 
} 
0

是的,你可以肯定做到这一点。我不会为此使用内联onclick属性。简单地说,添加事件监听器,然后打开窗口,用户分数从localStorage以及您的文本。

<li class="fa fa-twitter" id="tweet"></li> 
<script> 
$('#tweet').on('click', function(e){ 
    var score = localStorage.getItem('userScore'); 
    var tweetTxt = 'I just scored ' + score + ' on this game!'; 
    window.open('https://twitter.com/intent/tweet?text='+encodeURIComponent(tweetTxt), 'newwindow', 'width=300, height=250') 
}); 
</script> 
0

保持清晰和简单。

tweetScore = function() { 
 
    var score = localStorage.getItem('score'); 
 
    var text = 'I just score '+ score + ' on this game!'; 
 
    /* var options = 
 
    { width: 300; height:200, ... } 
 
    */ 
 
    var url = 'https://twitter.com/intent/tweet?text='+text; 
 
    
 
    window.open(url, 'newwindow', 'width=300,height=200'); 
 
    // or fetch them from options 
 
    return 0; 
 
}
<li class="fa fa-twitter" onclick="tweetScore()"> 
 
    tweet 
 
</li>

顺便说一句,你也可以单独的URL从tweetScore()功能形成。

urlCreator = function(foo) { 
//some operations 
//var url = foo+.. 
return url; 
} 

然后用它的返回值在tweetScore()

tweetScore = function() { 
    var score = localStorage.getItem('score'); 
    var text = 'I just score '+ score + ' on this game!'; 
    /* var options = 
    { width: 300; height:200, ... } 
    */ 
    var url = createUrl(text); 
    ... 

您还可以通过传递参数,扩展它 - 这将让你鸣叫很多东西,而不仅仅是分数。

tweetThis(arg1) { 
    //process arg1 
    //createUrl 
} 
相关问题