

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>chrome &#8211; Max的程式語言筆記</title>
	<atom:link href="https://stackoverflow.max-everyday.com/tag/chrome/feed/" rel="self" type="application/rss+xml" />
	<link>https://stackoverflow.max-everyday.com</link>
	<description>我要當一個豬頭，快樂過每一天</description>
	<lastBuildDate>Fri, 21 Feb 2025 10:44:16 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://stackoverflow.max-everyday.com/wp-content/uploads/2017/02/max-stackoverflow-256.png</url>
	<title>chrome &#8211; Max的程式語言筆記</title>
	<link>https://stackoverflow.max-everyday.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>chrome extension &#8220;manifest_version&#8221;: 3 , 使用 chrome.declarativeNetRequest.updateDynamicRules(roles,function(){}); 來阻止瀏覽器下載特定網址</title>
		<link>https://stackoverflow.max-everyday.com/2025/02/chrome-extension-manifest_version-3-block-url-fail/</link>
					<comments>https://stackoverflow.max-everyday.com/2025/02/chrome-extension-manifest_version-3-block-url-fail/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 21 Feb 2025 10:44:14 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6346</guid>

					<description><![CDATA[希望可以擋掉這個 url: https://te...]]></description>
										<content:encoded><![CDATA[
<p>希望可以擋掉這個 url: https://test.sg/js/ads.js?v=20241127200620, 在 rule.condition.urlFilter = &#8220;*test.sg/js/ads.* 但是實際瀏覽網頁, 檔案還是被瀏覽器下載</p>



<p>您好，針對您在使用 Chrome 擴充功能 <code>chrome.declarativeNetRequest.updateDynamicRules</code> 嘗試阻擋特定網址 <code>https://test.sg/js/ads.js?v=20241127200620</code> 時遇到的問題，以下是一些可能的解決方案和注意事項：</p>



<p><strong>1. 精確匹配 URL：</strong></p>



<ul class="wp-block-list">
<li>您的 <code>rule.condition.urlFilter = "*test.sg/js/ads.*"</code> 可能過於寬鬆。由於 URL 中包含查詢參數 <code>?v=20241127200620</code>，因此僅使用 <code>*test.sg/js/ads.*</code> 可能無法完全匹配。</li>



<li>嘗試使用更精確的匹配模式，例如：
<ul class="wp-block-list">
<li><code>rule.condition.urlFilter = "test.sg/js/ads.js?v=20241127200620"</code> (完全匹配)</li>



<li><code>rule.condition.urlFilter = "test.sg/js/ads.js"</code> (匹配不帶查詢參數的版本)</li>



<li><code>rule.condition.urlFilter = "test.sg/js/ads*"</code> (匹配任何以ads開頭的資源)</li>
</ul>
</li>



<li>如果查詢參數的值會變動，您可以使用更複雜的匹配模式，例如正規表達式。</li>
</ul>



<p><strong>2. 使用正規表達式：</strong></p>



<ul class="wp-block-list">
<li><code>declarativeNetRequest</code> 支援使用正規表達式進行更靈活的 URL 匹配。</li>



<li>您可以嘗試使用以下正規表達式：
<ul class="wp-block-list">
<li><code>rule.condition.regexFilter = "test\\.sg\\/js\\/ads\\.js\\?v=.*"</code></li>



<li>請注意，在正規表達式中，特殊字元（如 <code>.</code> 和 <code>?</code>）需要進行轉義。</li>
</ul>
</li>
</ul>



<p><strong>3. 檢查規則的優先順序：</strong></p>



<ul class="wp-block-list">
<li>如果您的擴充功能中有多個 <code>declarativeNetRequest</code> 規則，請確保您的阻擋規則具有足夠高的優先順序。</li>



<li><code>rule.priority</code> 屬性用於設定規則的優先順序，數值越小，優先順序越高。</li>
</ul>



<p><strong>4. 檢查規則的動作類型：</strong></p>



<ul class="wp-block-list">
<li>確保您的規則的 <code>rule.action.type</code> 屬性設定為 <code>"block"</code>，以阻止請求。</li>
</ul>



<p><strong>5. 檢查擴充功能的權限：</strong></p>



<ul class="wp-block-list">
<li>確保您的擴充功能在 <code>manifest.json</code> 檔案中具有足夠的權限。</li>



<li>您需要 <code>declarativeNetRequest</code> 和 <code>declarativeNetRequestWithHostAccess</code> 權限，以及對目標網域的 host permissions。</li>



<li>範例: JSON<code>"permissions": [ "declarativeNetRequest", "declarativeNetRequestWithHostAccess" ], "host_permissions": [ "*://*.test.sg/*" ]</code></li>
</ul>



<p><strong>6. 檢查 Chrome 版本：</strong></p>



<ul class="wp-block-list">
<li><code>declarativeNetRequest</code> API 在 Chrome 84 及更高版本中可用。</li>



<li>確保您的 Chrome 瀏覽器版本足夠新。</li>
</ul>



<p><strong>7. 偵錯方法：</strong></p>



<ul class="wp-block-list">
<li>使用 Chrome 的開發人員工具（DevTools）的 &#8220;Network&#8221; 標籤來檢查網路請求，確認 <code>ads.js</code> 檔案是否被下載，以及請求的詳細資訊。</li>



<li>您可以使用 <code>chrome.declarativeNetRequest.getDynamicRules</code> 來檢查您的擴充功能是否成功新增了規則。</li>



<li>您可以使用chrome://net-export/來紀錄網路事件，以方便除錯。</li>
</ul>



<p><strong>範例程式碼：</strong></p>



<p>JavaScript</p>



<pre class="wp-block-code"><code>chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: &#91;1], // 移除現有規則（如果存在）
  addRules: &#91;{
    "id": 1,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "test.sg/js/ads.js?v=20241127200620",
      "resourceTypes": &#91;"script"] // 只阻擋腳本
    }
  }]
}, function() {
  console.log("規則已更新");
});
</code></pre>



<p>請根據您的實際情況調整程式碼，並仔細檢查您的擴充功能權限和 Chrome 版本。希望這些資訊能幫助您解決問題。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>以上面的範例, 修改成阻止下列的url: </p>



<pre class="wp-block-code"><code>&#91;"*.doubleclick.net/*",
"*.ssp.hinet.net/*",
"*a.amnet.tw/*",
"*adx.c.appier.net/*",
"*cdn.cookielaw.org/*",
"*clarity.ms/*"]</code></pre>



<p>好的，以下是如何修改範例程式碼，以阻擋您提供的 URL 列表：</p>



<p><strong>1. 修改 <code>manifest.json</code>：</strong></p>



<p>首先，確保您的 <code>manifest.json</code> 檔案中有足夠的權限：</p>



<p>JSON</p>



<pre class="wp-block-code"><code>{
  "manifest_version": 3,
  "name": "URL Blocker",
  "version": "1.0",
  "permissions": &#91;
    "declarativeNetRequest",
    "declarativeNetRequestWithHostAccess"
  ],
  "host_permissions": &#91;
    "*://*.doubleclick.net/*",
    "*://*.ssp.hinet.net/*",
    "*://*.amnet.tw/*",
    "*://*.adx.c.appier.net/*",
    "*://*.cdn.cookielaw.org/*",
    "*://*.clarity.ms/*"
  ],
  "background": {
    "service_worker": "background.js"
  }
}
</code></pre>



<p><strong>2. 修改 <code>background.js</code>：</strong></p>



<p>然後，修改 <code>background.js</code> 檔案，以新增多個規則：</p>



<p>JavaScript</p>



<pre class="wp-block-code"><code>const urlsToBlock = &#91;
  "*.doubleclick.net/*",
  "*.ssp.hinet.net/*",
  "*a.amnet.tw/*",
  "*adx.c.appier.net/*",
  "*cdn.cookielaw.org/*",
  "*clarity.ms/*"
];

const rules = urlsToBlock.map((url, index) =&gt; ({
  "id": index + 1,
  "priority": 1,
  "action": { "type": "block" },
  "condition": {
    "urlFilter": url,
    "resourceTypes": &#91;"main_frame", "sub_frame", "script", "image", "stylesheet", "object", "xmlhttprequest", "other"] // 阻擋所有資源類型
  }
}));

chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: rules.map(rule =&gt; rule.id), // 移除現有規則
  addRules: rules
}, function() {
  console.log("規則已更新");
});
</code></pre>



<p><strong>程式碼說明：</strong></p>



<ul class="wp-block-list">
<li><strong><code>urlsToBlock</code> 陣列：</strong> 包含了您要阻擋的 URL 列表。</li>



<li><strong><code>rules</code> 陣列：</strong> 使用 <code>map</code> 函式將 URL 列表轉換為 <code>declarativeNetRequest</code> 規則陣列。
<ul class="wp-block-list">
<li>每個規則都有一個唯一的 <code>id</code>（從 1 開始）。</li>



<li><code>priority</code> 設定為 1，表示高優先順序。</li>



<li><code>action.type</code> 設定為 <code>"block"</code>，表示阻擋請求。</li>



<li><code>condition.urlFilter</code> 設定為要阻擋的 URL。</li>



<li><code>resourceTypes</code> 設定為阻擋所有資源類型，可以依據需求進行調整。</li>
</ul>
</li>



<li><strong><code>chrome.declarativeNetRequest.updateDynamicRules</code>：</strong>
<ul class="wp-block-list">
<li><code>removeRuleIds</code> 移除所有現有規則。</li>



<li><code>addRules</code> 新增 <code>rules</code> 陣列中的規則。</li>
</ul>
</li>
</ul>



<p><strong>注意事項：</strong></p>



<ul class="wp-block-list">
<li>請確保您的 Chrome 瀏覽器版本支援 <code>declarativeNetRequest</code> API。</li>



<li>擴充功能權限非常重要，請仔細檢查 <code>manifest.json</code> 中的 <code>permissions</code> 和 <code>host_permissions</code>。</li>



<li>您可以使用 Chrome 開發人員工具的 &#8220;Network&#8221; 標籤來驗證 URL 是否被成功阻擋。</li>



<li>resourceTypes可以依據需求調整，例如只阻擋script檔案，可以將resourceTypes設定為[&#8220;script&#8221;].</li>
</ul>



<p>希望這些資訊對您有幫助。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2025/02/chrome-extension-manifest_version-3-block-url-fail/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>javascript playsound chrome extension Manifest V3</title>
		<link>https://stackoverflow.max-everyday.com/2024/10/javascript-playsound-chrome-extension-manifest-v3/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/10/javascript-playsound-chrome-extension-manifest-v3/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Tue, 29 Oct 2024 10:26:41 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5977</guid>

					<description><![CDATA[如何在 chrome extension 裡播放...]]></description>
										<content:encoded><![CDATA[
<p> 如何在 chrome extension 裡播放音樂：</p>



<ul class="wp-block-list">
<li>Chrome Extension V3 offscreen audio not working due to &#8220;Receiving end does not exist.&#8221;<br><a href="https://stackoverflow.com/questions/78110557/chrome-extension-v3-offscreen-audio-not-working-due-to-receiving-end-does-not-e">https://stackoverflow.com/questions/78110557/chrome-extension-v3-offscreen-audio-not-working-due-to-receiving-end-does-not-e</a><br>附註：上面網址裡附的範例，有 typo 錯誤，<code>message</code> 應該改為 <code>msg</code> </li>



<li>Play audio from background script in chrome extention manifest v3<br><a href="https://stackoverflow.com/questions/67437180/play-audio-from-background-script-in-chrome-extention-manifest-v3">https://stackoverflow.com/questions/67437180/play-audio-from-background-script-in-chrome-extention-manifest-v3</a></li>
</ul>



<p></p>



<p>程式碼：</p>



<p><code>manifest.json</code></p>



<pre class="wp-block-code"><code>...
"permissions": &#91;"offscreen"]
...
</code></pre>



<p><code>background.js</code></p>



<pre class="wp-block-code"><code>/**
 * Plays audio files from extension service workers
 * @param {string} source - path of the audio file
 * @param {number} volume - volume of the playback
 */
async function playSound(source = 'default.wav', volume = 1) {
    await createOffscreen();
    await chrome.runtime.sendMessage({ play: { source, volume } });
}

// Create the offscreen document if it doesn't already exist
async function createOffscreen() {
    if (await chrome.offscreen.hasDocument()) return;
    await chrome.offscreen.createDocument({
        url: 'offscreen.html',
        reasons: &#91;'AUDIO_PLAYBACK'],
        justification: 'testing' // details for using the API
    });
}
</code></pre>



<p><code>offscreen.html</code></p>



<pre class="wp-block-code"><code>&lt;script src="offscreen.js"&gt;&lt;/script&gt;
</code></pre>



<p><code>offscreen.js</code></p>



<pre class="wp-block-code"><code>// Listen for messages from the extension
chrome.runtime.onMessage.addListener(msg =&gt; {
    if ('play' in msg) playAudio(msg.play);
});

// Play sound with access to DOM APIs
function playAudio({ source, volume }) {
    const audio = new Audio(source);
    audio.volume = volume;
    audio.play();
}</code></pre>



<p></p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/10/javascript-playsound-chrome-extension-manifest-v3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Chrome Extension: Uncaught ReferenceError: $ is not defined</title>
		<link>https://stackoverflow.max-everyday.com/2024/08/chrome-extension-uncaught-referenceerror-is-not-defined/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/08/chrome-extension-uncaught-referenceerror-is-not-defined/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 30 Aug 2024 01:27:11 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5913</guid>

					<description><![CDATA[一直鬼打牆，遇到這一個錯誤訊息，明明前幾分鐘還可...]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="199" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/08/Screenshot-2024-08-30-at-9.24.35 AM-1024x199.png?v=1724981195" alt="" class="wp-image-5914" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/08/Screenshot-2024-08-30-at-9.24.35 AM-1024x199.png?v=1724981195 1024w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/08/Screenshot-2024-08-30-at-9.24.35 AM-600x117.png?v=1724981195 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/08/Screenshot-2024-08-30-at-9.24.35 AM-768x149.png?v=1724981195 768w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/08/Screenshot-2024-08-30-at-9.24.35 AM.png?v=1724981195 1132w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>一直鬼打牆，遇到這一個錯誤訊息，明明前幾分鐘還可以使用，現在又不行。</p>



<p>即使加了下面的程式碼：</p>



<pre class="wp-block-code"><code>var $ = jQuery;</code></pre>



<p>會變成 jQuery is not defined</p>



<p>問題發生的原因是，「同一個 url pattern 在多個 matches」被使用，第二個 matched 的 js 會出問題。</p>



<p>會出現錯誤的manifest.json 設定：</p>



<pre class="wp-block-code"><code>{
    "matches": &#91;
        "https://max.com/*/*/*"
    ],
    "run_at": "document_end",
    "world": "MAIN",
    "js": &#91;
        "jquery.min.js",
        "js/main_next.js"
    ]
},
{
    "matches": &#91;
        "https://max.com/*/*/*"
    ],
    "run_at": "document_end",
    "js": &#91;
        "jquery.min.js",
        "js/main.js"
    ]
},</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>執行正常的設定：</p>



<pre class="wp-block-code"><code>{
    "matches": &#91;
        "https://max.com/*/*/*"
    ],
    "run_at": "document_end",
    "js": &#91;
        "jquery.min.js",
        "js/main.js"
    ]
},
{
    "matches": &#91;
        "https://max.com/*/*/*"
    ],
    "run_at": "document_end",
    "world": "MAIN",
    "js": &#91;
        "jquery.min.js",
        "js/main_next.js"
    ]
},</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/08/chrome-extension-uncaught-referenceerror-is-not-defined/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>chrome cdp Input.dispatchKeyEventchrome</title>
		<link>https://stackoverflow.max-everyday.com/2024/04/chrome-cdp-input-dispatchkeyeventchrome/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/04/chrome-cdp-input-dispatchkeyeventchrome/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Sat, 06 Apr 2024 04:58:40 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[selenium]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5634</guid>

					<description><![CDATA[由於 nodriver 暫時還無法送出 Ente...]]></description>
										<content:encoded><![CDATA[
<p>由於 nodriver 暫時還無法送出 Enter，解法：</p>



<pre class="wp-block-code"><code>await tab.send(cdp.input_.dispatch_key_event("keyDown", code="Enter", key="Enter", text="\r", windows_virtual_key_code=13))
await tab.send(cdp.input_.dispatch_key_event("keyUp", code="Enter", key="Enter", text="\r", windows_virtual_key_code=13))</code></pre>



<p>nodriver 程式碼：<br><a href="https://github.com/ultrafunkamsterdam/nodriver/blob/main/nodriver/cdp/input_.py">https://github.com/ultrafunkamsterdam/nodriver/blob/main/nodriver/cdp/input_.py</a></p>



<p>DrissionPage 程式碼：<br>DrissionPage/DrissionPage/_functions/keys.py<br><a href="https://github.com/g1879/DrissionPage/blob/master/DrissionPage/_functions/keys.py">https://github.com/g1879/DrissionPage/blob/master/DrissionPage/_functions/keys.py</a></p>



<pre class="wp-block-code"><code>def send_key(page, modifier, key):
    """发送一个字，在键盘中的字符触发按键，其它直接发送文本"""
    if key not in keyDefinitions:
        page.run_cdp('Input.insertText', text=key, _ignore=AlertExistsError)

    else:
        description = keyDescriptionForString(modifier, key)
        text = description&#91;'text']
        data = {'type': 'keyDown' if text else 'rawKeyDown',
                'modifiers': modifier,
                'windowsVirtualKeyCode': description&#91;'keyCode'],
                'code': description&#91;'code'],
                'key': description&#91;'key'],
                'text': text,
                'autoRepeat': False,
                'unmodifiedText': text,
                'location': description&#91;'location'],
                'isKeypad': description&#91;'location'] == 3,
                '_ignore': AlertExistsError}

        page.run_cdp('Input.dispatchKeyEvent', **data)
        data&#91;'type'] = 'keyUp'
        page.run_cdp('Input.dispatchKeyEvent', **data)</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/04/chrome-cdp-input-dispatchkeyeventchrome/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Google Chrome memory saver &#8211; command line switch?</title>
		<link>https://stackoverflow.max-everyday.com/2024/04/google-chrome-memory-saver-command-line-switch/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/04/google-chrome-memory-saver-command-line-switch/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 04 Apr 2024 22:28:29 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[selenium]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5628</guid>

					<description><![CDATA[如何手動啟用chrome 瀏覽器「Memory ...]]></description>
										<content:encoded><![CDATA[
<p>如何手動啟用chrome 瀏覽器「Memory Saver」, 解法：<br><a href="https://stackoverflow.com/questions/76938654/google-chrome-memory-saver-command-line-switch">https://stackoverflow.com/questions/76938654/google-chrome-memory-saver-command-line-switch</a></p>



<p>The setting seems to be here:&nbsp;<code>"C:\Users\&lt;username&gt;\AppData\Local\Google\Chrome\User Data\Local State"</code></p>



<pre class="wp-block-code"><code>{
    "autofill": {
        "states_data_dir": "C:\\Users\\&lt;username&gt;\\AppData\\Local\\Google\\Chrome\\User Data\\AutofillStates\\2020.11.2.164946"
    },
    "background_mode": {
        "enabled": false
    },
    "browser": {
        "enabled_labs_experiments": &#91;
            "memory-saver-multi-state-mode@1"
        ],
        "has_shown_refresh_2023_whats_new": true,
        "last_redirect_origin": "",
        "last_whats_new_version": 119,
        "shortcut_migration_version": "86.0.4240.75"
    },
    "data_use_measurement": {
        "data_used": {
            "services": {
                "background": {},
                "foreground": {}
.....
</code></pre>



<p>With the setting on&nbsp;<code>Default</code>&nbsp;it shows:&nbsp;<code>"browser":{"enabled_labs_experiments":[]</code></p>



<p><code>Enabled</code>&nbsp;shows:&nbsp;<code>"enabled_labs_experiments": ["memory-saver-multi-state-mode@1"]</code></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>寫入 Local Data 的範例程式碼：</p>



<pre class="wp-block-code"><code>def nodriver_overwrite_prefs(conf):
    state_filepath = os.path.join(conf.user_data_dir,"Local State")
    state_dict = {}
    state_dict&#91;"performance_tuning"]={}
    state_dict&#91;"performance_tuning"]&#91;"high_efficiency_mode"]={}
    state_dict&#91;"performance_tuning"]&#91;"high_efficiency_mode"]&#91;"state"]=1
    state_dict&#91;"browser"]={}
    state_dict&#91;"browser"]&#91;"enabled_labs_experiments"]=&#91;
        "memory-saver-multi-state-mode@1",
        "modal-memory-saver@1"
    ]
    json_str = json.dumps(state_dict)
    with open(state_filepath, 'w') as outfile:
        outfile.write(json_str)</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/04/google-chrome-memory-saver-command-line-switch/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to change preferences in Chrome by modifying files?</title>
		<link>https://stackoverflow.max-everyday.com/2024/04/how-to-change-preferences-in-chrome-by-modifying-files/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/04/how-to-change-preferences-in-chrome-by-modifying-files/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 04 Apr 2024 20:07:34 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[selenium]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5625</guid>

					<description><![CDATA[如何修改 chrome 的預設參數，資料來源：h...]]></description>
										<content:encoded><![CDATA[
<p>如何修改 chrome  的預設參數，資料來源：<br><a href="https://superuser.com/questions/554233/how-to-change-preferences-in-chrome-by-modifying-files">https://superuser.com/questions/554233/how-to-change-preferences-in-chrome-by-modifying-files</a></p>



<p>解法：</p>



<p>There is a file called &#8220;Preferences&#8221; within the &#8220;User Data/&lt;Profile&gt;&#8221; folder that appears to contain these settings. The location of this file varies according to OS. For the &#8220;Default&#8221; profile this is located at:</p>



<h3 class="wp-block-heading">WinXP:</h3>



<pre class="wp-block-code"><code>C:\Documents and Settings\&lt;User Name&gt;\Local Settings\Application Data\Google\Chrome\User Data\Default\Preferences
</code></pre>



<h3 class="wp-block-heading">WinVista:</h3>



<pre class="wp-block-code"><code>C:\Users\&lt;User Name&gt;\AppData\Local\Google\Chrome\User Data\Default\Preferences
</code></pre>



<p>You then need to search for the appropriate setting in that file. I would close Chrome (and backup) first as this file appears to be updated automatically as you navigate tabs.</p>



<p>&#8220;<strong>Enable Auto-fill to fill in web forms in a single click.</strong>&#8221; appears to be stored here:</p>



<pre class="wp-block-code"><code>   "autofill": {
      "enabled": true,
</code></pre>



<p>&#8220;<strong>Offer to save passwords I enter on the web.</strong>&#8220;</p>



<pre class="wp-block-code"><code>      "password_manager_enabled": true,</code></pre>



<p></p>



<p>Deploy initial preferences:<br><a href="https://support.google.com/chrome/a/answer/187948?hl=en#zippy=%2Cstep-create-the-initial-preferences-file">https://support.google.com/chrome/a/answer/187948?hl=en#zippy=%2Cstep-create-the-initial-preferences-file</a></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>寫入 Preferences 的程式碼：</p>



<pre class="wp-block-code"><code>def nodriver_overwrite_prefs(conf, prefs_dict={}):
    prefs_filepath = os.path.join(conf.user_data_dir,"Default")
    if not os.path.exists(prefs_filepath):
        os.mkdir(prefs_filepath)
    prefs_filepath = os.path.join(prefs_filepath,"Preferences")
    prefs_dict&#91;"profile"]={}
    prefs_dict&#91;"profile"]&#91;"name"]=CONST_APP_VERSION
    prefs_dict&#91;"profile"]&#91;"password_manager_enabled"]=False
    json_str = json.dumps(prefs_dict)
    with open(prefs_filepath, 'w') as outfile:
        outfile.write(json_str)</code></pre>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/04/how-to-change-preferences-in-chrome-by-modifying-files/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>chrome.scripting.executescript multiple functions</title>
		<link>https://stackoverflow.max-everyday.com/2024/01/chrome-scripting-executescript-multiple-functions/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/01/chrome-scripting-executescript-multiple-functions/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 03 Jan 2024 03:59:52 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5322</guid>

					<description><![CDATA[executeScript 的那個 functi...]]></description>
										<content:encoded><![CDATA[
<p>executeScript 的那個 function name 是OK 的,但其他的 function 並不會同時被一起 inject 進 web page.</p>



<p>解法:<br><a href="https://developer.chrome.com/docs/extensions/reference/api/scripting">https://developer.chrome.com/docs/extensions/reference/api/scripting</a></p>



<p>有問題範例:</p>



<pre class="wp-block-code"><code>function getTabId() { ... }<br>function getUserColor() { ... }<br><br>function changeBackgroundColor() {<br>&nbsp; document.body.style.backgroundColor = getUserColor();<br>}<br><br>chrome.scripting<br>&nbsp; &nbsp; .executeScript({<br>&nbsp; &nbsp; &nbsp; target : {tabId : getTabId()},<br>&nbsp; &nbsp; &nbsp; func : changeBackgroundColor,<br>&nbsp; &nbsp; })<br>&nbsp; &nbsp; .then(() =&gt; console.log("injected a function"));</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>使用 File 來 inject 也滿方便:</p>



<p>Files are specified as strings that are paths relative to the extension&#8217;s root directory. The following code will inject the file&nbsp;<code>script.js</code>&nbsp;into the main frame of the tab.</p>



<pre class="wp-block-code"><code>function getTabId() { ... }<br><br>chrome.scripting<br>&nbsp; &nbsp; .executeScript({<br>&nbsp; &nbsp; &nbsp; target : {tabId : getTabId()},<br>&nbsp; &nbsp; &nbsp; files : &#91; "script.js" ],<br>&nbsp; &nbsp; })<br>&nbsp; &nbsp; .then(() =&gt; console.log("injected script file"));</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>取得 inject 結果:</p>



<p>The results of executing JavaScript are passed to the extension. A single result is included per-frame. The main frame is guaranteed to be the first index in the resulting array; all other frames are in a non-deterministic order.</p>



<pre class="wp-block-code"><code>function getTabId() { ... }<br>function getTitle() { return document.title; }<br><br>chrome.scripting<br>&nbsp; &nbsp; .executeScript({<br>&nbsp; &nbsp; &nbsp; target : {tabId : getTabId(), allFrames : true},<br>&nbsp; &nbsp; &nbsp; func : getTitle,<br>&nbsp; &nbsp; })<br>&nbsp; &nbsp; .then(injectionResults =&gt; {<br>&nbsp; &nbsp; &nbsp; for (const {frameId, result} of injectionResults) {<br>&nbsp; &nbsp; &nbsp; &nbsp; console.log(`Frame ${frameId} result:`, result);<br>&nbsp; &nbsp; &nbsp; }<br>&nbsp; &nbsp; });</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/01/chrome-scripting-executescript-multiple-functions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>extension manifest must request permission to access this host. manifest 3</title>
		<link>https://stackoverflow.max-everyday.com/2024/01/extension-manifest-must-request-permission-to-access-this-host-manifest-3/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/01/extension-manifest-must-request-permission-to-access-this-host-manifest-3/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 03 Jan 2024 03:34:39 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5320</guid>

					<description><![CDATA[在使用 chrome.scripting.exe...]]></description>
										<content:encoded><![CDATA[
<p>在使用 chrome.scripting.executeScript() 時顯示無權限存取這個作用中的分頁.</p>



<p>解法:<br><a href="https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions">https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions</a></p>



<p>manifest.json</p>



<pre class="wp-block-code"><code>&nbsp; "host_permissions": &#91;<br>&nbsp; &nbsp; "https://www.developer.chrome.com/*"<br>&nbsp; ],<br>&nbsp; "optional_host_permissions":&#91;<br>&nbsp; &nbsp; "https://*/*",<br>&nbsp; &nbsp; "http://*/*"<br>&nbsp; ],</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/01/extension-manifest-must-request-permission-to-access-this-host-manifest-3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Chrome extension tab.url undefined</title>
		<link>https://stackoverflow.max-everyday.com/2024/01/chrome-extension-tab-url-undefined/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/01/chrome-extension-tab-url-undefined/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 03 Jan 2024 03:31:37 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5317</guid>

					<description><![CDATA[在判斷做用中的分頁範列程式碼裡, 想取得 tab...]]></description>
										<content:encoded><![CDATA[
<p>在判斷做用中的分頁範列程式碼裡, 想取得 tab.url 會出現 undefined, 程式碼:</p>



<pre class="wp-block-code"><code>chrome.tabs.query({active: true, currentWindow: true}, (tabs) =>{
    // Do something
});</code></pre>



<p>輸出作用中的tab:</p>



<figure class="wp-block-image size-full"><img decoding="async" width="1006" height="512" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/01/chrome_2024-01-03_11-03_7c.png?v=1704251027" alt="" class="wp-image-5318" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/01/chrome_2024-01-03_11-03_7c.png?v=1704251027 1006w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/01/chrome_2024-01-03_11-03_7c-600x305.png?v=1704251027 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/01/chrome_2024-01-03_11-03_7c-768x391.png?v=1704251027 768w" sizes="(max-width: 1006px) 100vw, 1006px" /></figure>



<p>解法:<br><a href="https://copyprogramming.com/howto/chrome-extension-get-url-of-active-tab">https://copyprogramming.com/howto/chrome-extension-get-url-of-active-tab</a></p>



<p>增加 &#8220;tabs&#8221; permission:</p>



<pre class="wp-block-code"><code>"permissions": &#91;
"tabs"
],</code></pre>



<p>PS: 當 focus 不在任何tab 時, 也會出現 undefined.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/01/chrome-extension-tab-url-undefined/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to import a js file in a Chrome extension service worker?</title>
		<link>https://stackoverflow.max-everyday.com/2024/01/how-to-import-a-js-file-in-a-chrome-extension-service-worker/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/01/how-to-import-a-js-file-in-a-chrome-extension-service-worker/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 03 Jan 2024 01:56:13 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5309</guid>

					<description><![CDATA[這個問題的解法: Migrate to a se...]]></description>
										<content:encoded><![CDATA[
<p>這個問題的解法:</p>



<p>Migrate to a service worker<br><a href="https://developer.chrome.com/docs/extensions/develop/migrate/to-service-workers">https://developer.chrome.com/docs/extensions/develop/migrate/to-service-workers</a></p>



<p>沒想到這麼快就來到 JS 的 module 的世界。</p>



<p>透過下列程式碼, 讓 service worker 持續上班:</p>



<p>Use the following code snippet to keep your service worker alive:</p>



<pre class="wp-block-code"><code>/**<br>&nbsp;* Tracks when a service worker was last alive and extends the service worker<br>&nbsp;* lifetime by writing the current time to extension storage every 20 seconds.<br>&nbsp;* You should still prepare for unexpected termination - for example, if the<br>&nbsp;* extension process crashes or your extension is manually stopped at<br>&nbsp;* chrome://serviceworker-internals. <br>&nbsp;*/<br>let heartbeatInterval;<br><br>async function runHeartbeat() {<br>&nbsp; await chrome.storage.local.set({ 'last-heartbeat': new Date().getTime() });<br>}<br><br>/**<br>&nbsp;* Starts the heartbeat interval which keeps the service worker alive. Call<br>&nbsp;* this sparingly when you are doing work which requires persistence, and call<br>&nbsp;* stopHeartbeat once that work is complete.<br>&nbsp;*/<br>async function startHeartbeat() {<br>&nbsp; // Run the heartbeat once at service worker startup.<br>&nbsp; runHeartbeat().then(() =&gt; {<br>&nbsp; &nbsp; // Then again every 20 seconds.<br>&nbsp; &nbsp; heartbeatInterval = setInterval(runHeartbeat, 20 * 1000);<br>&nbsp; });<br>}<br><br>async function stopHeartbeat() {<br>&nbsp; clearInterval(heartbeatInterval);<br>}<br><br>/**<br>&nbsp;* Returns the last heartbeat stored in extension storage, or undefined if<br>&nbsp;* the heartbeat has never run before.<br>&nbsp;*/<br>async function getLastHeartbeat() {<br>&nbsp; return (await chrome.storage.local.get('last-heartbeat'))&#91;'last-heartbeat'];<br>}</code></pre>



<p>service worker 的 console.log 要透過這裡去看:</p>



<p>chrome://serviceworker-internals</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Extension service worker basics<br><a href="https://developer.chrome.com/docs/extensions/develop/concepts/service-workers/basics#import-scripts">https://developer.chrome.com/docs/extensions/develop/concepts/service-workers/basics#import-scripts</a></p>



<p>To use the&nbsp;<code>import</code>&nbsp;statement, add the&nbsp;<code>"type"</code>&nbsp;field to your manifest and specify&nbsp;<code>"module"</code>. For example:</p>



<pre class="wp-block-code"><code>&nbsp; "background": {<br>&nbsp; &nbsp; "service_worker": "service-worker.js",<br>&nbsp; &nbsp; "type": "module"<br>&nbsp; }</code></pre>



<p>Then use&nbsp;<code>import</code>&nbsp;as you normally would. Note that import assertions are not supported.</p>



<pre class="wp-block-code"><code>import { tldLocales } from './locales.js';</code></pre>



<p>Use&nbsp;<code>importScripts()</code>&nbsp;as you would in a web service worker.</p>



<pre class="wp-block-code"><code>importScripts('locales.js');</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>範例:</p>



<p>Sample CO₂ Meter Chrome Extension<br><a href="https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.co2meter">https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.co2meter</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/01/how-to-import-a-js-file-in-a-chrome-extension-service-worker/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
