inject-tools.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import Settings from '../options/settings.js';
  2. export default (() => {
  3. /**
  4. * 如果tabId指定的tab还存在,就正常注入脚本
  5. * @param tabId 需要注入脚本的tabId
  6. * @param codeConfig 需要注入的代码
  7. * @param callback 注入代码后的callback
  8. */
  9. let injectScriptIfTabExists = function (tabId, codeConfig, callback) {
  10. chrome.tabs.query({currentWindow: true}, (tabs) => {
  11. tabs.some(tab => {
  12. if (tab.id !== tabId) return false;
  13. Settings.getOptions((opts) => {
  14. if (!codeConfig.hasOwnProperty('allFrames')) {
  15. codeConfig.allFrames = String(opts['CONTENT_SCRIPT_ALLOW_ALL_FRAMES']) === 'true';
  16. }
  17. codeConfig.code = 'try{' + codeConfig.code + ';}catch(e){};';
  18. // 有文件就注入文件
  19. if(codeConfig.files && codeConfig.files.length){
  20. // 注入样式
  21. if(codeConfig.files.join(',').indexOf('.css') > -1) {
  22. chrome.scripting.insertCSS({
  23. target: {tabId, allFrames: codeConfig.allFrames},
  24. files: codeConfig.files
  25. }, function () {
  26. callback && callback.apply(this, arguments);
  27. });
  28. }
  29. // 注入js
  30. else {
  31. chrome.scripting.executeScript({
  32. target: {tabId, allFrames: codeConfig.allFrames},
  33. files: codeConfig.files
  34. }, function () {
  35. chrome.scripting.executeScript({
  36. target: {tabId, allFrames: codeConfig.allFrames},
  37. func: function(code){evalCore.getEvalInstance(window)(code)},
  38. args: [codeConfig.code]
  39. }, function () {
  40. callback && callback.apply(this, arguments);
  41. });
  42. });
  43. }
  44. }else{
  45. // 没有文件就只注入脚本
  46. chrome.scripting.executeScript({
  47. target: {tabId, allFrames: codeConfig.allFrames},
  48. func: function(code){evalCore.getEvalInstance(window)(code)},
  49. args: [codeConfig.code]
  50. }, function () {
  51. callback && callback.apply(this, arguments);
  52. });
  53. }
  54. });
  55. return true;
  56. });
  57. });
  58. };
  59. return { inject: injectScriptIfTabExists };
  60. })();