【问题标题】:I want to execute the code which I have fetched from the server. I can get the code in my console. Want that code to execute on the main browser page我想执行从服务器获取的代码。我可以在控制台中获取代码。希望该代码在浏览器主页面上执行
【发布时间】:2019-06-25 22:18:38
【问题描述】:

所以,我有一个非常基本的 Google Chrome 扩展程序,其中有一个按钮。我正在浏览器控制台中的服务器上使用 AJAX 获取脚本。因此,当我单击扩展程序时,会出现一个按钮,当我单击该按钮时 - 它会从服务器获取脚本,并且我可以使用 console.log 在控制台上加载该脚本

我想做的是,我想在当前页面上运行该脚本。

所以我的问题是 - 如何使该脚本在我的页面上运行,该页面已加载到浏览器的控制台中?

这是我的按钮的基本 HTML 代码 -


<h4>Click here</h4>

<button class="button button5" id="bt1" >
  <img src="a.png" alt="Click Me" style="height:42px;border:0;">
</button>

这是我从服务器获取脚本的基本 JS 代码 -


var buttonClick = document.getElementById('bt1');
buttonClick.addEventListener('click', loadDoc('https://abcd/xyz/pqr/Script1', myFunction));


function loadDoc(url, cFunction) {
  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = this.responseText;
      cFunction(this);



      chrome.tabs.getSelected(null,function(tab) {


      chrome.tabs.executeScript({code: `console.log(${JSON.stringify(data)})`});
      chrome.tabs.getCurrent('data');
      //console.log(taburl);
     });
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

所以,基本上,我已将该脚本加载到“数据”变量中

所以,现在,我必须从控制台复制该脚本并将其粘贴到我的控制台中,以便脚本执行并且我在当前浏览器页面上看到结果/输出。

因此,我想要的是,而不是复制和粘贴来运行它 - 当我点击我的扩展程序中的按钮时,脚本应该自动在页面上运行/执行。

【问题讨论】:

    标签: javascript html css ajax google-chrome-extension


    【解决方案1】:

    我不确定你会如何使用 chrome 扩展来做到这一点。但是,您可以使用小书签运行 javascript。这些行为类似于书签,但它们不是重定向,而是运行代码。您可以使用this website将代码转换为书签

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 2019-09-16
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多